我試圖將一個函數接收一個文件路徑,確定它是什么,設置適當的標頭,并像Apache一樣提供服務。我這樣做的原因是因為在提供文件之前,我需要使用PHP處理有關請求的某些信息。速度至關重要virtual()不是一個選擇必須在用戶無法控制Web服務器(Apache / nginx等)的共享托管環境中工作到目前為止,這是我得到的:File::output($path);<?phpclass File {static function output($path) { // Check if the file exists if(!File::exists($path)) { header('HTTP/1.0 404 Not Found'); exit(); } // Set the content-type header header('Content-Type: '.File::mimeType($path)); // Handle caching $fileModificationTime = gmdate('D, d M Y H:i:s', File::modificationTime($path)).' GMT'; $headers = getallheaders(); if(isset($headers['If-Modified-Since']) && $headers['If-Modified-Since'] == $fileModificationTime) { header('HTTP/1.1 304 Not Modified'); exit(); } header('Last-Modified: '.$fileModificationTime); // Read the file readfile($path); exit();}static function mimeType($path) { preg_match("|\.([a-z0-9]{2,4})$|i", $path, $fileSuffix); switch(strtolower($fileSuffix[1])) { case 'js' : return 'application/x-javascript'; case 'json' : return 'application/json'; case 'jpg' : case 'jpeg' : case 'jpe' : return 'image/jpg'; case 'png' : case 'gif' : case 'bmp' : case 'tiff' : return 'image/'.strtolower($fileSuffix[1]); case 'css' : return 'text/css'; case 'xml' : return 'application/xml'; case 'doc' : case 'docx' : return 'application/msword'; case 'xls' : case 'xlt' : case 'xlm' : case 'xld' : case 'xla' : case 'xlc' : case 'xlw' : case 'xll' : return 'application/vnd.ms-excel'; case 'ppt' : case 'pps' : return 'application/vnd.ms-powerpoint'; case 'rtf' : return 'application/rtf';?>
3 回答

SMILET
TA貢獻1796條經驗 獲得超4個贊
最快的方法:不要。查看nginx的x-sendfile標頭,其他Web服務器也有類似的內容。這意味著您仍然可以在php中進行訪問控制等,但是將文件的實際發送委托給為此設計的Web服務器。
PS:我覺得不寒而栗,只是想與在php中讀取和發送文件相比,將它與nginx結合使用會更有效率。試想一下,如果有100個人正在下載文件:使用php + apache,那么慷慨,那大概是100 * 15mb = 1.5GB(大約,給我射擊),就在那兒。Nginx只會將文件發送到內核,然后將其直接從磁盤加載到網絡緩沖區中。迅速!
PPS:而且,使用這種方法,您仍然可以執行所有訪問控制和所需的數據庫工作。
添加回答
舉報
0/150
提交
取消