在PHP中使用X-SendFile頭讓文件下載更快
一般來說, 我們可以通過直接讓URL指向一個位于Document Root下面的文件, 來引導(dǎo)用戶下載文件.
但是, 這樣做, 就沒辦法做一些統(tǒng)計, 權(quán)限檢查, 等等的工作. 于是, 很多時候, 我們采用讓PHP來做轉(zhuǎn)發(fā), 為用戶提供文件下載.
<?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);
但是這個有一個問題, 就是如果文件是中文名的話, 有的用戶可能下載后的文件名是亂碼.
于是, 我們做一下修改:
<?php
$file = "/tmp/中文名.tar.gz";
$filename = basename($file);
header("Content-type: application/octet-stream");
//處理中文文件名
$ua = $_SERVER["HTTP_USER_AGENT"];
$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 . '"');
}
header("Content-Length: ". filesize($file));
readfile($file);
恩, 現(xiàn)在看起來好多了, 不過還有一個問題, 那就是readfile, 雖然PHP的readfile嘗試實(shí)現(xiàn)的盡量高效, 不占用PHP本身的內(nèi)存, 但是實(shí)際上它還是需要采用MMAP(如果支持), 或者是一個固定的buffer去循環(huán)讀取文件, 直接輸出.
輸出的時候, 如果是Apache + PHP mod, 那么還需要發(fā)送到Apache的輸出緩沖區(qū). 最后才發(fā)送給用戶. 而對于Nginx + fpm如果他們分開部署的話, 那還會帶來額外的網(wǎng)絡(luò)IO.
那么, 能不能不經(jīng)過PHP這層, 直接讓W(xué)ebserver直接把文件發(fā)送給用戶呢?
今天, 我看到了一個有意思的文章: How I PHP: X-SendFile.
我們可以使用Apache的module mod_xsendfile, 讓Apache直接發(fā)送這個文件給用戶:
<?php
$file = "/tmp/中文名.tar.gz";
$filename = basename($file);
header("Content-type: application/octet-stream");
//處理中文文件名
$ua = $_SERVER["HTTP_USER_AGENT"];
$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發(fā)送文件
header("X-Sendfile: $file");
X-Sendfile頭將被Apache處理, 并且把響應(yīng)的文件直接發(fā)送給Client.
Lighttpd和Nginx也有類似的模塊, 大家有興趣的可以去找找看
相關(guān)文章

php 數(shù)組處理函數(shù)extract詳解及實(shí)例代碼

基于Discuz security.inc.php代碼的深入分析

用PHP寫的MySQL數(shù)據(jù)庫用戶認(rèn)證系統(tǒng)代碼

php+ajax導(dǎo)入大數(shù)據(jù)時產(chǎn)生的問題處理

Yii2 中實(shí)現(xiàn)單點(diǎn)登錄的方法

淺析Yii2 GridView實(shí)現(xiàn)下拉搜索教程

PHP session文件獨(dú)占鎖引起阻塞問題解決方法