让PHP更快的提供文件下载的代码

前端之家收集整理的这篇文章主要介绍了让PHP更快的提供文件下载的代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

但是,这样做,就没办法做一些统计,权限检查,等等的工作. 于是,很多时候,我们采用让PHP来做转发,为用户提供文件下载. @H_301_0@<div class="codetitle"><a style="CURSOR: pointer" data="31151" class="copybut" id="copybut31151" onclick="doCopy('code31151')"> 代码如下:

<div class="codebody" id="code31151"> @H_301_0@<?PHP @H_3010@$file = "/tmp/dummy.tar.gz"; @H3010@header("Content-type: application/octet-stream"); @H3010@header('Content-Disposition: attachment; filename="' . basename($file) . '"'); @H3010@header("Content-Length: ". filesize($file)); @H3010@readfile($file); @H3010@
@H301_0@但是这个有一个问题,就是如果文件中文名的话,有的用户可能下载后的文件名是乱码. 于是,我们做一下修改(参考: : @H_301_0@<div class="codetitle"><a style="CURSOR: pointer" data="22866" class="copybut" id="copybut22866" onclick="doCopy('code22866')"> 代码如下:
<div class="codebody" id="code22866"> @H_301_0@<?PHP @H_301_0@$file = "/tmp/中文名.tar.gz"; @H_3010@$filename = basename($file); @H3010@header("Content-type: application/octet-stream"); @H301_0@//处理中文文件名 @H_301_0@$ua = $_SERVER["HTTP_USERAGENT"]; @H301_0@$encodedfilename = urlencode($filename); @H301_0@$encoded_filename = str_replace("+","%20",$encodedfilename); @H301_0@if (pregmatch("/MSIE/",$ua)) { @H301_0@header('Content-Disposition: attachment; filename="' . $encodedfilename . '"'); @H301_0@} else if (pregmatch("/Firefox/",$ua)) { @H3010@header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"'); @H3010@} else { @H3010@header('Content-Disposition: attachment; filename="' . $filename . '"'); @H3010@} @H3010@header('Content-Disposition: attachment; filename="' . $filename . '"'); @H3010@header("Content-Length: ". filesize($file)); @H3010@readfile($file); @H3010@
@H301_0@恩,现在看起来好多了,不过还有一个问题,那就是readfile,虽然PHP的readfile尝试实现的尽量高效,不占用PHP本身的内存,但是实际上它还是需要采用MMAP(如果支持),或者是一个固定的buffer去循环读取文件,直接输出. 输出的时候,如果是Apache + PHP mod,那么还需要发送到Apache的输出缓冲区. 最后才发送给用户. 而对于Nginx + fpm如果他们分开部署的话,那还会带来额外的网络IO. 那么,能不能不经过PHP这层,直接让Webserver直接把文件发送给用户呢? @H_301_0@

今天,我看到了一个有意思的文章: How I PHP: X-SendFile.

我们可以使用Apache的module mod_xsendfile,让Apache直接发送这个文件用户:

代码如下:
301_0@PHP @H_301_0@$file = "/tmp/中文名.tar.gz"; @H_301_0@$filename = basename($file); @H_301_0@header("Content-type: application/octet-stream"); @H_301_0@//处理中文文件名 @H_301_0@$ua = $_SERVER["HTTP_USER_AGENT"]; @H_301_0@$encoded_filename = urlencode($filename); @H_301_0@$encoded_filename = str_replace("+",$ua)) { @H_301_0@header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"'); @H_301_0@} else { @H_301_0@header('Content-Disposition: attachment; filename="' . $filename . '"'); @H_301_0@} @H_301_0@header('Content-Disposition: attachment; filename="' . basename($file) . '"'); @H_301_0@//让Xsendfile发送文件 @H_301_0@header("X-Sendfile: $file"); @H_301_0@
@H_301_0@X-Sendfile头将被Apache处理,并且把响应的文件直接发送给Client. @H_301_0@Lighttpd和Nginx也有类似的模块,大家有兴趣的可以去找找看

猜你在找的PHP相关文章