問題描述
我用 PHP 創(chuàng)建了一個(gè)文件下載腳本,它可以工作,但網(wǎng)絡(luò)瀏覽器將文件報(bào)告為未知長(zhǎng)度".我的代碼如下:
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 網(wǎng)站通過一個(gè)強(qiáng)大的 PHP 腳本來驗(yàn)證下載,類似于 Andrew Johnson 發(fā)布的腳本在 他關(guān)于 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 在文章末尾發(fā)表了一個(gè)非常重要的評(píng)論:
Andrew makes a very important comment at the end of the article:
"如果您使用 Zlib、mod_deflate 等壓縮文件,則 Content-Length 標(biāo)頭將不準(zhǔn)確,因此您最終會(huì)看到未知大小"和剩余時(shí)間未知"下載文件時(shí)."
"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."
我想強(qiáng)調(diào)一點(diǎn):如果您的瀏覽器似乎沒有遵守由您的 PHP 腳本生成的標(biāo)頭——尤其是 Content-Length
——很可能是 Apache 的 mod_deflate
擴(kuò)展已啟用.
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
文件中的以下行輕松為單個(gè)腳本禁用它:
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 位于服務(wù)器根目錄路徑中的下載腳本中(例如 www.crimsonbase.com/download.php
).(那是因?yàn)檎齽t表達(dá)式是^/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
.)
這篇關(guān)于使用 PHP 下載腳本發(fā)送正確的文件大小的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!