background image

PHP 教程: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

 = urlencode(

$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''" . 

$filename

 . '"'); 

else

 { 

header('Content-Disposition: attachment; filename="' . 

$filename

 . '"'); 


header('Content-Disposition: attachment; filename="' . 

$filename

 . '"'); 

header("Content-Length: ". 

filesize

(

$file

)); 

readfile(

$file

); 

 

, 现在看起来好多了, 不过还有一个问题, 那就是 readfile, 虽然 PHP 的 readfile 尝试实现的

尽量高效

, 不占用 PHP 本身的内存, 但是实际上它还是需要采用 MMAP(如果支持), 或者是