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

Roc*_*mat 9 php browser cross-browser download

我在PHP中创建了一个文件下载脚本,它可以工作,但是Web浏览器将文件报告为"未知长度".我的代码如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

小智 15

最初来自http://paul.luminos.nl/update/471:

CrimsonBase网站在其中加入类似于安德鲁·约翰逊在发布的一个强大的PHP脚本验证下载了他对PHP控制文件下载的文章.

安德鲁在文章末尾做了一个非常重要的评论:

"如果使用Zlib压缩文件,mod_deflate等内容长度标题将不准确,因此下载文件时最终会看到"未知大小"和"未知剩余时间".

我想强调一点:如果您的浏览器似乎没有遵守PHP脚本生成的标头 - 特别是Content-Length-it很可能是Apache的mod_deflate扩展已启用.

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

SetEnvIfNoCase Request_URI ^/download\.php no-gzip dont-vary
Run Code Online (Sandbox Code Playgroud)

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


Sky*_*ner 9

我有同样的问题,我通过在Content-Length之前发送标题来修复它Content-Disposition.

header('Content-Type: video/mp4');
header("Content-Transfer-Encoding: Binary"); 
header("Content-Length: ".filesize($file_url));
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url);
Run Code Online (Sandbox Code Playgroud)