使用 PHP 下载脚本发送正确的文件大小
我用 PHP 创建了一个文件下载脚本,它可以工作,但网络浏览器将文件报告为未知长度".我的代码如下:
I created a file download script in PHP, it works, but web browsers report the file as "Unknown Length". My code is as follows:
function downloadFile($file){
// Set up the download system...
header('Content-Description: File Transfer');
header('Content-Type: '.mime_content_type($file));
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: '.filesize($file));
// Flush the cache
ob_clean();
flush();
// Send file to browser
readfile($file);
// DO NOT DO ANYTHING AFTER FILE DOWNLOAD
exit;
}
推荐答案
原文来自 http://paul.luminos.nl/update/471:
CrimsonBase 网站通过一个强大的 PHP 脚本来验证下载,类似于 Andrew Johnson 发布的脚本在 他关于 PHP 控制的文件下载的文章中.
The CrimsonBase website verifies downloads by passing them through a robust PHP script similar to the one published by Andrew Johnson in his article about PHP-controlled file downloads.
Andrew 在文章末尾发表了一个非常重要的评论:
Andrew makes a very important comment at the end of the article:
"如果您使用 Zlib、mod_deflate 等压缩文件,则 Content-Length 标头将不准确,因此您最终会看到未知大小"和剩余时间未知"下载文件时."
"If you compress files with Zlib, mod_deflate and so on the Content-Length header won't be accurate so you'll end up seeing "Unknown size" and "Unknown time remaining" when downloading files."
我想强调一点:如果您的浏览器似乎没有遵守由您的 PHP 脚本生成的标头——尤其是 Content-Length
——很可能是 Apache 的 mod_deflate
扩展已启用.
I would like to stress this: if your browser doesn't appear to be obeying the headers generated by your PHP script—especially Content-Length
—it is fairly likely that Apache's mod_deflate
extension is enabled.
您可以使用适用的 .htaccess
文件中的以下行轻松为单个脚本禁用它:
You can easily disable it for a single script using the following line in an applicable .htaccess
file:
SetEnvIfNoCase Request_URI ^/download.php no-gzip dont-vary
此处假定 download.php 位于服务器根目录路径中的下载脚本中(例如 www.crimsonbase.com/download.php
).(那是因为正则表达式是^/download.php
.)
where download.php is here assumed to be in the download script located in the server's root directory path (e.g. www.crimsonbase.com/download.php
). (That's because the regular expression is ^/download.php
.)
相关文章