您好,欢迎访问一九零五行业门户网

PHP实现点击a标签的href做链接时,直接保存文件(任何类型),而

一、 index.php中: ?php echo a href='process.php?filename=halo.mp3'下载/a? process.php中: ?php header(content-type: application/octet-stream);header('content-disposition: attachment; filename='. basename($_get['filename']).'');header(cont
一、
index.php中:

process.php中:
这是最简单的方法,但是有个问题:如果请求的路径中包含中文,那么下载的文件名有可能就是乱码。二、
针对上面问题的解决方案,index.php中:

process.php中:

输出的时候,如果是apache+php,那么还需要发送到apache的输出缓冲区,最后才发送给用户。而对于nginx+fpm,如果它们分开部署的话,那还会带来额外的网络io。三、
现在貌似没有问题了,但是readfile还是有问题的,虽然php的readfile尝试实现的尽量高效,不占用php本身的内存,但是实际上它还是需要采用mmap(如果支持),或者是一个固定的buffer去循环读取文件,直接输出。
那么能不能绕过php这层呢,直接由webserver把文件发送给用户呢?可以的,我们可以使用apache的module mode_xsendfile,让apache直接发送这个文件给用户。
代码实现如下:(process.php)
header(content-type: application/octet-stream);//处理中文文件名$ua = $_server[http_user_agent];$encoded_filename = urlencode($_get['filename']);$encoded_filename = str_replace(+, %20, $encoded_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'' . $_get['filename'] . '');} else {header('content-disposition: attachment; filename=' . $_get['filename'] . '');}//让xsendfile发送文件 header(x-sendfile: $_get['filename']);
最后,如果愿意的话,可以先判断后缀,因为有时候图片当成文件下载也会引起一些不方便的: $type = strrchr($_get['filename'], .); //获取后缀 if($type == jpg || png || gif){ header(content-disposition: filename=$_get['filename']); //这里我试过,加引号的话,下载时会加到文件名中 header(content-type: image/$type); }
其它类似信息

推荐信息