php以不同名字下载同一个文件(x-sendfile)

1、linux 下nginx默认支持x-sendfile模式

Nginx 默认支持该特性,不需要加载额外的模块。需要发送的 HTTP 头为 X-Accel-Redirect。另外,需要在配置文件中做以下设定

location /protected/ {
  internal;
  root   /some/path;
}

internal 表示这个路径只能在 Nginx 内部访问,不能用浏览器直接访问防止未授权的下载。

PHP发送 X-Accel-Redirect 给 Nginx:

<?php
$filePath = '/protected/iso.img';
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
//让Xsendfile发送文件
header('X-Accel-Redirect: '.$filePath);
?>

这样用户就会下载到 /some/path/protected/iso.img 这个路径下的文件。

如果你想发送的是 /some/path/iso.img 文件,那么 Nginx 配置应该是

location /protected/ {
  internal;
  alias   /some/path/; # 注意最后的斜杠

}


2、windows下的apache,需要加载module mod_xsendfile

从https://tn123.org/mod_xsendfile/下载Win32 binaries,放到apache的modules目录下,在http.conf中配置

LoadModule xsendfile_module modules/mod_xsendfile.so
XSendFile On


<?php
$file = "/tmp/dummy.tar.gz";//要用绝对路径,windows下比如d:\tmp\
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header("X-Sendfile:".$file);

但是这个有一个问题, 就是如果文件是中文名的话, 有的用户可能下载后的文件名是乱码.

于是, 我们做一下修改(参考: :

<?php
$file = "/tmp/中文名.tar.gz";

$filename = basename($file);

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

//处理中文文件名
if (strpos($_SERVER["HTTP_USER_AGENT"],"MSIE") === false)
    header('Content-Disposition: attachment; filename="' . ($name) . '"');
else
    header('Content-Disposition: attachment; filename="' . rawurlencode($name) . '"');

//让Xsendfile发送文件
header("X-Sendfile: $file");


X-Sendfile头将被Apache处理, 并且把响应的文件直接发送给Client.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值