woff 發表於 2010-4-23 00:40:46

PHP利用header做檔案下載控制

這筆者本人有測試過的
很多公家機關都會要求要讓使用者下載 Microsoft Office 檔案的功能,但是 Internet Explorer 總是會自作聰明的幫你打開,哪要如何做到這個功能呢?


其實這個是要在 HTTP Header 的 Content-Disposition 加一個 「attachment;」 在檔名的前面。
以 PHP 為例就是:
header( "Content-Disposition: attachment; filename=xxx.doc;" );
以下是 PHP 完整的下載範例,記得「副檔名一定要限定,不然伺服器上很多重要的檔案都會被別人下載看光光了」。
<?
$filename = $_GET['file'];
/*
也可以在這裡可以加上路徑,如改為 $filename = "/download/".$_GET['file'];
*/

$ext = substr($filename,-3 );
echo $filename;
if( $filename == "" ) {
echo "<html><body>未指定檔案路徑及名稱!</body></html>";
exit;
} elseif ( ! file_exists( $filename ) ) {
echo "<html><body>找不到檔案!</body></html>";
exit;
};
switch ($ext) {
    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;
default:echo "<html><body>您不可下載這個檔案</body></html>";
exit();
}

header('Content-Description: File Transfer');
header("Content-Type: $ctype");
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: cache, must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean();
flush();
readfile($filename);
exit;
?>


補充:
•ontent-Disposition: attachment;filename: 這是給瀏覽器看的檔案名稱,也就是下載視窗會出現的那個檔名;它可以跟實際檔案的名稱不一樣!
•readfile($filename): 會連到實際檔案的位置,也就是該檔案在伺服器上的真實路徑。
•Content-Length: ' . filesize($filename): 檔案的大小。
若php.ini 的 memory_limit 設的太小,會造成網頁一直在讀取, 不會跳出下載視窗的問題。
注意點:要確認一下php.ini中php5.5預設的output_buffering是output_buffering = Off的話,將它修改成如下
    output_buffering = 4096
;output_buffering = Off

woff 發表於 2010-4-29 00:15:42

檔案有修改過

這是正確版本
頁: [1]
查看完整版本: PHP利用header做檔案下載控制