伺服器提供一個檔案下載,一般使用一個url指向伺服器中的檔案即可提供下載。
但這樣就不能進行統計,許可權檢測等操作。
因此,一般使用php提供下載,代碼如下:
<?php $file = 'test.zip'; if(file_exists($file)){ header('content-type:application/octet-stream'); header('content-disposition:attachment; filename='.basename($file)); header('content-length:'.filesize($file)); readfile($file); } ?>
處理中文檔案名稱:
<?php $file = 'test.zip'; $filename = '中文.zip'; if(file_exists($file)){ $user_agent = $_SERVER['Http_User_agent']; $encode_filename = rawurlencode($filename); if(preg_match("/MSIE/", $user_agent)){ header('content-disposition:attachment; filename="'.$encode_filename.'"'); }else if(preg_match("/Firefox/", $user_agent)){ header("content-disposition:attachment; filename*=\"utf8''".$filename.'"'); }else{ header('content-disposition:attachment; filename="'.$filename.'"'); } readfile($file); } ?>
更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/PHP/
使用php readfile,需要經過php這層,如果可以直接通過apache將檔案發送給使用者,不經過php這層,將會提高下載速度。
使用apache mod_xsendfile,下載地址:mod_xsendfile,讓apache直接將檔案發給使用者
安裝:
sudo apxs2 -cia mod_xsendfile.c sudo a2enmod xsendfile sudo /etc/init.d/apache2 restart
apxs2 用於編譯apache module,需要安裝apache2-dev
設定xsendfile開啟:
<Directory> XSendFile On </Directory>
代碼如下:
<?php $file = 'test.zip'; $filename = '中文.zip'; if(file_exists($file)){ $user_agent = $_SERVER['Http_User_agent']; $encode_filename = rawurlencode($filename); if(preg_match("/MSIE/", $user_agent)){ header('content-disposition:attachment; filename="'.$encode_filename.'"'); }else if(preg_match("/Firefox/", $user_agent)){ header("content-disposition:attachment; filename*=\"utf8''".$filename.'"'); }else{ header('content-disposition:attachment; filename="'.$filename.'"'); } header('X-Sendfile:'.$file); } ?>