function dl_file($file){
//檢查檔案是否存在
if (!is_file($file)) { die("404 File not found!"); }
//取得檔案相關資料
$len = filesize($file);
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
//將檔案格式設定為將要下載的檔案
switch( $file_extension ) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
case "mp3": $ctype="audio/mpeg"; break;
case "wav": $ctype="audio/x-wav"; break;
case "mpeg":
case "mpg":
case "mpe": $ctype="video/mpeg"; break;
case "mov": $ctype="video/quicktime"; break;
case "avi": $ctype="video/x-msvideo"; break;
//禁止下面幾種類型的檔案被下載
case "php":
case "htm":
case "html":
case "txt": die("Cannot be used for ". $file_extension ." files!"); break;
default: $ctype="application/force-download";
}
//開始編寫header
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
//使用利用 switch判別的檔案類型
header("Content-Type: $ctype");
//執行下載動作
$header="Content-Disposition: attachment; filename=".$filename.";";
header($header );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$len);
@readfile($file);
exit;
}
?>
但是如果你只是純粹想要單純一點更改下載檔案的部份的話,只需要這樣:
$saveasname = "excel95.xls"; //要被儲存成的檔名
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; Filename="'.$saveasname.'"');
readfile($saveasname);
?>
readfile是把檔案的內容讀到網頁中,header就會把網頁內容丟到給你下載的檔案裏面,甚至如果你需要對檔案做壓縮再下載的話,可以利用:
$saveasname = "test.txt.gz";
//Header設定
header('Content-Encoding:x-gzip');
header('Content-Type: application/x-gzip');
header('Content-Disposition: attachment; Filename="'.$saveasname.'"');
header('Pragma: no-cache');
//要輸出的內容用gzencode函式處理過
echo gzencode('hi', 9);
?>
header還有許多各種不同的對網頁做控制的功能,詳情請詳閱PHP官方網站XD~
例如將上面其中的
header('Content-Type: application/x-gzip');
改成
header("Content-Type: application/force-download");
就可以讓使用者變成強制直接儲存檔案,不能讓他單純只使用預覽,等等的功能
是個非常實用的函數喔^^"
沒有留言:
張貼留言