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: mp 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.

原文地址:http://blog.csdn.net/ownfire/article/details/11522213

原文地址:https://www.cnblogs.com/hejia/p/4058495.html