一般來說, 我們可以通過直接讓URL指向一個位於Document Root下面的文件, 來引導用戶下載文件.但是, 這樣做, 就沒辦法做一些統計, 權限檢查, 等等的工作. 於是, 很多時候, 我們採用讓PHP來做轉發, 爲用戶提供文件下載
1 | $file = "/tmp/dummy.tar.gz" ; |
2 | header( "Content-type: application/octet-stream" ); |
3 | header( 'Content-Disposition: attachment; filename="' . basename ( $file ) . '"' ); |
4 | header( "Content-Length: " . filesize ( $file )); |
但是這個有一個問題, 就是如果文件是中文名的話, 有的用戶可能下載後的文件名是亂碼.
於是, 我們做一下修改(參考: :
01 |
$file = "/tmp/中文名.tar.gz" ; |
02 |
$filename = basename ( $file ); |
03 |
header( "Content-type: application/octet-stream" ); |
05 |
$ua = $_SERVER [ "HTTP_USER_AGENT" ]; |
06 |
$encoded_filename = urlencode( $filename ); |
07 |
$encoded_filename = str_replace ( "+" , "%20" , $encoded_filename ); |
08 |
if (preg_match( "/MSIE/" , $ua )) { |
09 |
header( 'Content-Disposition: attachment; filename="' . $encoded_filename . '"' ); |
10 |
} else if (preg_match( "/Firefox/" , $ua )) { |
11 |
header( "Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"' ); |
13 |
header( 'Content-Disposition: attachment; filename="' . $filename . '"' ); |
16 |
header( 'Content-Disposition: attachment; filename="' . $filename . '"' ); |
17 |
header( "Content-Length: " . filesize ( $file )); |
恩, 現在看起來好多了, 不過還有一個問題, 那就是readfile, 雖然PHP的readfile嘗試實現的儘量高效, 不佔用PHP本身的內存, 但是實際上它還是需要採用MMAP(如果支持), 或者是一個固定的buffer去循環讀取文件, 直接輸出.
輸出的時候, 如果是Apache + PHP mod, 那麼還需要發送到Apache的輸出緩衝區. 最後才發送給用戶. 而對於Nginx + fpm如果他們分開部署的話, 那還會帶來額外的網絡IO.
那麼, 能不能不經過PHP這層, 直接讓Webserver直接把文件發送給用戶呢?
我們可以使用Apache的module mod_xsendfile, 讓Apache直接發送這個文件給用戶:
01 |
$file = "/tmp/中文名.tar.gz" ; |
02 |
$filename = basename ( $file ); |
03 |
header( "Content-type: application/octet-stream" ); |
05 |
$ua = $_SERVER [ "HTTP_USER_AGENT" ]; |
06 |
$encoded_filename = urlencode( $filename ); |
07 |
$encoded_filename = str_replace ( "+" , "%20" , $encoded_filename ); |
08 |
if (preg_match( "/MSIE/" , $ua )) { |
09 |
header( 'Content-Disposition: attachment; filename="' . $encoded_filename . '"' ); |
10 |
} else if (preg_match( "/Firefox/" , $ua )) { |
11 |
header( "Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"' ); |
13 |
header( 'Content-Disposition: attachment; filename="' . $filename . '"' ); |
15 |
header( 'Content-Disposition: attachment; filename="' . basename ( $file ) . '"' ); |
17 |
header( "X-Sendfile: $file" ); |
X-Sendfile頭將被Apache處理, 並且把響應的文件直接發送給Client.
文章來源:http://blog.51edm.org/post/110