gpt4 book ai didi

php - 使用 PHP 下载脚本发送正确的文件大小

转载 作者:可可西里 更新时间:2023-11-01 12:26:52 25 4
gpt4 key购买 nike

我在 PHP 中创建了一个文件下载脚本,它可以运行,但网络浏览器将文件报告为“未知长度”。我的代码如下:

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 :

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."

我想强调一点:如果您的浏览器似乎不遵守 PHP 脚本生成的 header ——尤其是 Content-Length——很可能是 Apache 的 mod_deflate 扩展已启用。

您可以在适用的 .htaccess 文件中使用以下行轻松地为单个脚本禁用它:

SetEnvIfNoCase Request_URI ^/download\.php no-gzip dont-vary

这里假定 download.php 位于服务器根目录路径中的下载脚本中(例如 www.crimsonbase.com/download.php)。 (那是因为正则表达式是 ^/download\.php。)

关于php - 使用 PHP 下载脚本发送正确的文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1972642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com