让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@ @H
301_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_USER
AGENT"]; @H301_0@$encoded
filename = urlencode($filename); @H301_0@$encoded_filename = str_replace("+","%20",$encoded
filename); @H301_0@if (preg
match("/MSIE/",$ua)) { @H301_0@header('Content-Disposition: attachment; filename="' . $encoded
filename . '"'); @H301_0@} else if (preg
match("/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@ .
缓冲区. 最后才发送给
. 而对于
+ fpm如果他们分开部署的话,那还会带来额外的网络IO. 那么,能不能不经过
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@
直接发送给Client. @H_