我試圖將一個(gè)函數(shù)接收一個(gè)文件路徑,確定它是什么,設(shè)置適當(dāng)?shù)臉?biāo)頭,并像Apache一樣提供服務(wù)。我這樣做的原因是因?yàn)樵谔峁┪募?,我需要使用PHP處理有關(guān)請(qǐng)求的某些信息。速度至關(guān)重要virtual()不是一個(gè)選擇必須在用戶無法控制Web服務(wù)器(Apache / nginx等)的共享托管環(huán)境中工作到目前為止,這是我得到的: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貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
最快的方法:不要。查看nginx的x-sendfile標(biāo)頭,其他Web服務(wù)器也有類似的內(nèi)容。這意味著您仍然可以在php中進(jìn)行訪問控制等,但是將文件的實(shí)際發(fā)送委托給為此設(shè)計(jì)的Web服務(wù)器。
PS:我覺得不寒而栗,只是想與在php中讀取和發(fā)送文件相比,將它與nginx結(jié)合使用會(huì)更有效率。試想一下,如果有100個(gè)人正在下載文件:使用php + apache,那么慷慨,那大概是100 * 15mb = 1.5GB(大約,給我射擊),就在那兒。Nginx只會(huì)將文件發(fā)送到內(nèi)核,然后將其直接從磁盤加載到網(wǎng)絡(luò)緩沖區(qū)中。迅速!
PPS:而且,使用這種方法,您仍然可以執(zhí)行所有訪問控制和所需的數(shù)據(jù)庫工作。
- 3 回答
- 0 關(guān)注
- 770 瀏覽
添加回答
舉報(bào)
0/150
提交
取消