使用PHP下载脚本发送正确的文件大小 [英] Sending correct file size with PHP download script
问题描述
我在PHP中创建了一个文件下载脚本,它的工作原理,但Web浏览器报告该文件为未知长度。我的代码如下:
function downloadFile($ file){
//设置下载系统。
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));
//刷新缓存
ob_clean();
flush();
//将文件发送到浏览器
readfile($ file);
//不要做任何后续文件下载
退出;
}
http://paul.luminos.nl/update/471 =nofollow noreferrer> http://paul.luminos.nl/update/471 :
CrimsonBase网站通过将下载传递给用户PHP脚本类似于Andrew Johnson在关于PHP控制的文件下载的文章。
Andrew在文章末尾做了非常重要的评论:
如果你使用Zlib,mod_deflate等压缩文件Content-Length头部不准确,所以你会看到未知大小和
我要强调的是:如果您的浏览器似乎没有遵守你的PHP脚本生成的头文件 - 特别是
Content-Length
-it很可能启用了Apache的mod_deflate
扩展。
您可以在适用的
.htaccess
文件中使用以下行简单地禁用单个脚本:SetEnvIfNoCase Request_URI ^ / download\.php no-gzip dont-vary
pre>
其中,download.php假设位于服务器根目录路径下的下载脚本中(例如
www.crimsonbase.com/download.php
)。 (这是因为正则表达式是^ / download\.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;
}
Originally from http://paul.luminos.nl/update/471:
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 makes a very important comment at the end of the article:
"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."
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'smod_deflate
extension is enabled.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
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
.)
这篇关于使用PHP下载脚本发送正确的文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!