項目中涉及到檔案的下載下傳功能,通常PHP檔案下載下傳都是将檔案先讀取出來然後發送相應頭檔案進行下載下傳。
如:
$file_dir = $instance->_attach_path.Helper_Hash::hashDIR($id).$attach['path'];
if(!file_exists($file_dir)){
throw new FromMeException('檔案不存在');
}
else{
// 打開檔案
$file = fopen($file_dir,"r");
// 輸入檔案标簽
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($file_dir));
Header("Content-Disposition: attachment; filename=" . $attach['name']);
// 輸出檔案内容
echo fread($file,filesize($file_dir));
fclose($file);
exit();
}
這種方式可以實作檔案的下載下傳,但是這種下載下傳方式相當耗資源,長期占用服務端腳本資源和伺服器記憶體資源,消耗很大。
後來查閱資料,我們可以借助X-sendfile子產品來實作更高效率的檔案下載下傳。
X-sendfile是現代作業系統支援的一種高性能網絡IO方式,服務端腳本程式比如php負責構造請求頭資訊,然後下載下傳的時候不需要php參與,web伺服器直接處理X-Sendfile頭資訊,并且把響應的檔案直接發送給浏覽器用戶端;這樣避免了記憶體占用。
首先我們要檢視Apache的版本資訊:
然後下載下傳對應的X-sendfile子產品包(下載下傳位址:https://github.com/nmaier/mod_xsendfile)。
1、将解壓出來的mod_xsendfile.so檔案拷貝到Apache的modules目錄下
2、配置Apache的conf目錄下的httpd.conf檔案,加入以下代碼:
LoadModule xsendfile_module modules/mod_xsendfile.so
XSendFile on
XSendFilePath F:/
3、重新開機Apache服務,通路phpinfo()檢視是否加載xsendfile子產品:
這些工作完成之後我們就可以借助X-sendfile來實作檔案下載下傳了:
$file_dir = $instance->_attach_path.Helper_Hash::hashDIR($id).$attach['path'];
if(!file_exists($file_dir)){
throw new FromMeException('檔案不存在');
}
else{
$ua = $_SERVER["HTTP_USER_AGENT"];
$filename = $attach['name'];
$encoded_filename = urlencode($filename);
$encoded_filename = str_replace("+", "%20", $encoded_filename);
// 輸入檔案标簽
$realpath = realpath($file_dir);
header('Content-Type: application/octet-stream');
//進行中文檔案名,避免檔案名亂碼
$encoded_filename = rawurlencode($filename);
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
} else {
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
//讓Xsendfile發送檔案
header("X-Sendfile: $realpath");
exit();
}
需要注意的是:X-sendfile發送的檔案路徑要是絕對路徑,不然會找不到。