当使用php下载文件时,使用php readfile,需要经过php这层,如果可以直接通过apache将文件发送给用户,不经过php这层,将会提高下载速度。X-sendfile是现代操作系统支持的一种高性能网络IO方式,服务端脚本程序比如php负责构造请求头信息,然后下载的时候不需要php参与,web服务器直接处理X-Sendfile头信息,并且把响应的文件直接发送给浏览器客户端;这样避免了内存占用。
【1】下载
https://tn123.org/mod_xsendfile/
【2】编译
apxs -cia mod_xsendfile.c
【3】查看httpd.conf
是否添加mod_xsendfile.so模块
LoadModule xsendfile_module modules/mod_xsendfile.so
【4】配置httpd-vhosts.conf
配置方式很多,这里表示.php后缀的文件可以使用xsendfile,使用的目录为/home/Env/TestSource
<Files *.php>
XSendFile on
XSendFilePath /home/Env/TestSource/
</Files>
【5】编码
public static function download($path, $fileName)
{
if(!isset($path) || !is_file($path))
return MODE_ERROR;
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
$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("X-Sendfile: " . $path);
}