問題描述
我用 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
.)
這篇關于使用 PHP 下載腳本發送正確的文件大小的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!