讓PHP更快的為使用者提供檔案下載

來源:互聯網
上載者:User

  一般來說,我們可以通過直接讓URL指向一個位於Document Root下面的檔案,來引導使用者下載檔案


但是,這樣做,就沒辦法做一些統計,許可權檢查,等等的工作。於是,很多時候,我們採用讓PHP來做轉寄,為使用者提供檔案下載


$file = “/tmp/dummy.tar.gz”;


header(“Content-type: application/octet-stream”);


header('Content-Disposition: attachment; filename=“' . basename($file) . '”');


header(“Content-Length: “. filesize($file));


readfile($file);


但是這個有一個問題,就是如果檔案是中文名的話,有的使用者可能下載後的檔案名稱是亂碼。


於是,我們做一下修改(參考: :


$file = “/tmp/中文名.tar.gz”;


$filename = basename($file);


header(“Content-type: application/octet-stream”);


//處理中文檔案名稱


$ua = $_SERVER[“HTTP_USER_AGENT”];


$encoded_filename = urlencode($filename);


$encoded_filename = str_replace(“+”, “%20”, $encoded_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 . '”');


}


header('Content-Disposition: attachment; filename=“' . $filename . '”');


header(“Content-Length: “. filesize($file));


readfile($file);


輸出的時候,如果是Apache + PHP mod,那麼還需要發送到Apache的輸出緩衝區。最後才發送給使用者。而對於Nginx + fpm如果他們分開部署的話,那還會帶來額外的網路IO。


恩,現在看起來好多了,不過還有一個問題,那就是readfile,雖然PHP的readfile嘗試實現的盡量高效,不佔用PHP本身的記憶體,但是實際上它還是需要採用MMAP(如果支援),或者是一個固定的buffer去迴圈讀取檔案,直接輸出。

  那麼,能不能不經過PHP這層,直接讓Webserver直接把檔案發送給使用者呢?


今天,我看到了一個有意思的文章:How I PHP:X-SendFile。


我們可以使用Apache的module mod_xsendfile,讓Apache直接發送這個檔案給使用者:


$file = “/tmp/中文名.tar.gz”;


$filename = basename($file);


header(“Content-type: application/octet-stream”);


//處理中文檔案名稱


$ua = $_SERVER[“HTTP_USER_AGENT”];


$encoded_filename = urlencode($filename);


$encoded_filename = str_replace(“+”, “%20”, $encoded_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 . '”');


}


header('Content-Disposition: attachment; filename=“' . basename($file) . '”');


//讓Xsendfile傳送檔案


header(“X-Sendfile: $file”);


Lighttpd和Nginx也有類似的模組,大家有興趣的可以去找找看。X-Sendfile頭將被Apache處理,並且把響應的檔案直接發送給Client。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.