PHP+nginx+sendfile实现大文件下载

作者: 站长 上传时间: 浏览: N/A 下载: N/A 格式: N/A 评分: N/A

首先我们需要确保我们的nginx开启了sendfile:

sendfile on;

然后我们还要在nginx配置文件中加上以下这段:
# 配置 sendfile
location /assets/uploads/ {
internal; # 表示这个路径只能在 Nginx 内部访问, 提高了安全性
root /phpProjects/mphf/mph-backend;
}

这个时候如果我们PHP代码中给的文件下载路径为/assets/uploads/a.pdf ,则表示我们的下载文件为 /phpProjects/mphf/mph-backend/assets/uploads/a.pdf 。这时我们的PHP端只需要做一些校验,兼容性处理的工作,处理完后通过 X-Accel-Redirect 将下载的事交给nginx处理就行了。

public function download($filename, $filePath){
// 校验通过后
header('Content-Type: application/octet-stream');
$ua = $_SERVER["HTTP_USER_AGENT"]; // 处理不同浏览器的兼容性
if (preg_match("/MSIE/", $ua) || preg_match("/rv:/", $ua)) {
$encoded_filename = rawurlencode($filename);
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-Accel-Redirect: '.$filePath);
}

Leave a Comment