程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php header函數下載文件實現代碼

php header函數下載文件實現代碼

編輯:關於PHP編程

在php中header函數的使用很大,header不但可以向客戶端發送原始的 HTTP 報頭信息,同時還可以直接實現文件下載操作,接下來小編給大家介紹歡迎各位朋友參考。

header函數最常用的不是用於下載而是用於發送http類的

跳轉

它會執行最後一個,不過是有條件的,例如:

 代碼如下 復制代碼

header('Location:http://www.bKjia.c0m");
header('Location:http://www.g.cn');
header('Location:http://www.baidu.com');

這個就會跳到百度

header('Location:http://www.bKjia.c0m');echo '幫客之家;
header('Location:http://www.g.cn');
header('Location:http://www.baidu.com');

這個就會跳到google


發送狀態

輸出狀態值到浏覽器,主要用於訪問權限控制

 代碼如下 復制代碼

<?php
header('HTTP/1.1 401 Unauthorized');
header('status: 401 Unauthorized');
?>

比如要限制一個用戶不能訪問該頁,則可設置狀態為404,如下所示,這樣浏覽器就顯示為即該頁不存在

 代碼如下 復制代碼

<?php
header('HTTP/1.1 404 Not Found');
header("status: 404 Not Found");
?>

下載


 代碼如下 復制代碼

<?php
$filename = '路徑+實際文件名';
//文件的類型
header('Content-type: application/pdf');
//下載顯示的名字
header('Content-Disposition: attachment; filename="保存時的文件名.pdf"');
readfile("$filename");
exit();
?>

header函數進行相應的轉化,

 代碼如下 復制代碼 header(‘Content-type: application/octet-stream’);//輸出的類型,根據下面提供的MIME表,選擇相應的類型
header(‘Content-Disposition: attachment; filename=”下載顯示名字.rar”‘);//下載顯示的名字
readfile(‘服務器上的文件名.rar’);//

要下的文件,包括路徑

常用的MIME類型
.doc    application/msword
.docx   application/vnd.openxmlformats-officedocument.wordprocessingml.document
.rtf    application/rtf
.xls    application/vnd.ms-excel application/x-excel
.xlsx   application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt    application/vnd.ms-powerpoint
.pptx   application/vnd.openxmlformats-officedocument.presentationml.presentation
.pps   application/vnd.ms-powerpoint
.ppsx  application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pdf   application/pdf
.swf   application/x-shockwave-flash
.dll   application/x-msdownload
.exe   application/octet-stream
.msi   application/octet-stream
.chm   application/octet-stream
.cab   application/octet-stream
.ocx   application/octet-stream
.rar  application/octet-stream
.tar  application/x-tar
.tgz  application/x-compressed
.zip  application/x-zip-compressed
.z    application/x-compress
.wav   audio/wav
.wma   audio/x-ms-wma
.wmv   video/x-ms-wmv
.mp3 .mp2 .mpe .mpeg .mpg   audio/mpeg
.rm   application/vnd.rn-realmedia
.mid .midi .rmi   audio/mid
.bmp   image/bmp
.gif   image/gif
.png   image/png
.tif .tiff    image/tiff
.jpe .jpeg .jpg    image/jpeg
.txt  text/plain
.xml  text/xml
.html text/html
.css  text/css
.js   text/javascript

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved