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

标签 php cross-browser browser download

我在 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/

相关文章:

php - Laravel:在 View 中使用模型关系是一个好的实践吗?

javascript - Internet Explorer 中模块的加载超时

html - Safari 占用提交按钮周围的空间

browser - 当用户在其网络浏览器中按下停止按钮时会发生什么?

javascript - 浏览器是读取/存储 Javascript 文件中的所有内容还是只读取/存储它们需要的内容?

php - 使用ajax获取javascript变量

PHP:执行怪异

php - 上传未保存的文件时为 "Trying to get property of non-object"

html - 现代网络浏览器可以并行下载哪些类型的网络资源?另外,什么不能并行下载?

java - Android 浏览器不适用于地理定位