<?php <br />
<br>
$file = "/tmp/dummy.tar.gz";<br>
<br>
header("Content-type: application/octet-stream");<br>
<br>
header('Content-Disposition: attachment; filename="' . basename($file) . '"');<br>
<br>
header("Content-Length: ". filesize($file));<br>
<br>
readfile($file);
但是这个有一个问题, 就是如果文件是中文名的话, 有的用户可能下载后的文件名是乱码.<?php <br />
<br>
$file = "/tmp/中文名.tar.gz";<br>
<br>
$filename = basename($file);<br>
<br>
header("Content-type: application/octet-stream");<br>
<br>
//处理中文文件名<br>
<br>
$ua = $_SERVER["HTTP_USER_AGENT"];<br>
<br>
$encoded_filename = urlencode($filename);<br>
<br>
$encoded_filename = str_replace("+", "%20", $encoded_filename);<br>
<br>
if (preg_match("/MSIE/", $ua)) {<br>
<br>
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');<br>
<br>
} else if (preg_match("/Firefox/", $ua)) {<br>
<br>
header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');<br>
<br>
} else {<br>
<br>
header('Content-Disposition: attachment; filename="' . $filename . '"');<br>
<br>
}<br>
<br>
header('Content-Disposition: attachment; filename="' . $filename . '"');<br>
<br>
header("Content-Length: ". filesize($file));<br>
<br>
readfile($file);
恩, 现在看起来好多了, 不过还有一个问题, 那就是readfile, 虽然PHP的readfile尝试实现的尽量高效, 不占用PHP本身的内存, 但是实际上它还是需要采用MMAP(如果支持), 或者是一个固定的buffer去循环读取文件, 直接输出. <?php <br />
<br>
$file = "/tmp/中文名.tar.gz";<br>
<br>
$filename = basename($file);<br>
<br>
header("Content-type: application/octet-stream");<br>
<br>
//处理中文文件名<br>
<br>
$ua = $_SERVER["HTTP_USER_AGENT"];<br>
<br>
$encoded_filename = urlencode($filename);<br>
<br>
$encoded_filename = str_replace("+", "%20", $encoded_filename);<br>
<br>
if (preg_match("/MSIE/", $ua)) {<br>
<br>
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');<br>
<br>
} else if (preg_match("/Firefox/", $ua)) {<br>
<br>
header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');<br>
<br>
} else {<br>
<br>
header('Content-Disposition: attachment; filename="' . $filename . '"');<br>
<br>
}<br>
<br>
header('Content-Disposition: attachment; filename="' . basename($file) . '"');<br>
<br>
//让Xsendfile发送文件<br>
<br>
header("X-Sendfile: $file");
X-Sendfile头将被Apache处理, 并且把响应的文件直接发送给Client.AD:真正免费,域名+虚机+企业邮箱=0元