Press "Enter" to skip to content

让PHP更快的提供文件下载

一般来说, 我们可以通过直接让URL指向一个位于Document Root下面的文件, 来引导用户下载文件.

但是, 这样做, 就没办法做一些统计, 权限检查, 等等的工作. 于是, 很多时候, 我们采用让PHP来做转发, 为用户提供文件下载.

<?php
    $file = "/tmp/dummy.tar.gz";
    header("Content-type: application/octet-stream");
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header("Content-Length: ". filesize($file));
    readfile($file);

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

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

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

    $filename = basename($file);

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

    //处理中文文件名
    $ua = $_SERVER["HTTP_USER_AGENT"];
    $encoded_filename = rawurlencode($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''" . $filename . '"');
    } else {
	header('Content-Disposition: attachment; filename="' . $filename . '"');
    }

    header("Content-Length: ". filesize($file));
    readfile($file);

恩, 现在看起来好多了, 不过还有一个问题, 那就是readfile, 虽然PHP的readfile尝试实现的尽量高效, 不占用PHP本身的内存, 但是实际上它还是需要采用MMAP(如果支持), 或者是一个固定的buffer去循环读取文件, 直接输出.

输出的时候, 如果是Apache + PHP mod, 那么还需要发送到Apache的输出缓冲区. 最后才发送给用户. 而对于Nginx + fpm如果他们分开部署的话, 那还会带来额外的网络IO.

那么, 能不能不经过PHP这层, 直接让Webserver直接把文件发送给用户呢?

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

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

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

    $filename = basename($file);

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

    //处理中文文件名
    $ua = $_SERVER["HTTP_USER_AGENT"];
    $encoded_filename = rawurlencode($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''" . $filename . '"');
    } else {
	header('Content-Disposition: attachment; filename="' . $filename . '"');
    }

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

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

Lighttpd和Nginx也有类似的模块, 大家有兴趣的可以去找找看 🙂

78 Comments

  1. 徐吉武
    徐吉武 2017-03-09

    $file = “/tmp/中文名.tar.gz”;

    $filename = basename($file);
    basename获取中文的文件名获取不到

  2. plansze szkolne
    plansze szkolne 2016-03-10

    If some one desires expert view about blogging afterward i propose him/her to pay a visit this web site, Keep up the nice work.

  3. winter outfits
    winter outfits 2015-12-15

    What’s up, for all time i used to check blog posts here in the early hours in the
    dawn, because i like to gain knowledge of more and more.

  4. Theda
    Theda 2015-01-11

    Very shortly this web site will be famous amid all blogging and site-building users,
    due too it’s fastidious articles or reviews

  5. […] 最近有点闲暇时间了,不小心看了@风雪之隅的一篇的文章《让PHP更快的提供文件下载》后,利用实际项目中的业务场景觉得有必须要去优化附件下载功能了。鸟哥的文章里面主要介绍的基于apache来做XSendfile讲解的,我有点强迫症,我对我的生产环境《顶岗实习管理系统》进行升级改造,我的webserver是nginx,所以基于nginx官方网站的XSendfile说明特做此改造笔记。 […]

  6. share112
    share112 2014-05-20

    见到一些网站 采用 下载 实体文件加上 token的方式 来下载 如xxxx.mp3?uijsd2342ewijl234, 感觉这种处理方法也能统计 比 X-Sendfile 更直接 些,但也说不上有什么优势。。

  7. 2013 at 4:41 pm
    2013 at 4:41 pm 2013-06-22

    Hey! I’m at work surfing around your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the great work!

  8. Luis
    Luis 2013-05-06

    Very nice article, just what I wanted to find.

    I am greatful that you taking a moment to see my information.

    You are free to consider a look at my very own web site also for
    more information and facts and effective suggestions: Luis

  9. I know this if off topic but I’m looking into starting my own weblog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty
    penny? I’m not very web smart so I’m not 100% sure. Any suggestions or advice would be greatly appreciated. Appreciate it

    I appreciate you currently taking a time period to evaluation my account. You are free to take a glimpse at my personal webpage also for extra info and valuable ideas … Pest Control Charlotte

  10. test
    test 2012-09-11

    大家有试下nginx的X-Accel-Redirect,当文件不存的情况吗,是不是会请求很多次?

  11. test
    test 2012-09-05

    header(“Location: “.$uri);和该方法的区别何在?

Leave a Reply

Your email address will not be published. Required fields are marked *