【问题标题】:Sending correct file size with PHP download script使用 PHP 下载脚本发送正确的文件大小
【发布时间】:2010-12-30 16:01:22
【问题描述】:

我在 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;
}

【问题讨论】:

    标签: php cross-browser browser download


    【解决方案1】:

    尽量不要在 readfile() 函数之前刷新缓存。我的代码与您的代码几乎相同,并且工作正常。

    【讨论】:

    • 试过了,没有。下载仍然可以正常工作,只是网络浏览器会说“未知文件大小”,即使我给它一个“内容长度”。问题是,如果我使用 wget,它会报告正确的文件大小。
    【解决方案2】:

    原文来自http://paul.luminos.nl/update/471

    CrimsonBase website 通过一个强大的 PHP 脚本验证下载,该脚本类似于 Andrew Johnson 在his article about PHP-controlled file downloads 中发布的脚本。

    Andrew 在文末发表了非常重要的评论:

    “如果您使用 Zlib、mod_deflate 等压缩文件,则 Content-Length 标头将不准确,因此您最终会在下载文件时看到“未知大小”和“剩余时间未知”。”

    我想强调一点:如果您的浏览器似乎没有遵循 PHP 脚本生成的标头(尤其是 Content-Length),则很有可能启用了 Apache 的 mod_deflate 扩展。

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

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

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

    【讨论】:

    • 有趣。我需要调查一下。
    • 谢谢,我在下载中得到了“gzip”内容类型,并且能够用您的 htaccess 行摆脱它,现在我可以再次看到下载进度,因为总文件大小被正确读取通过浏览器。
    【解决方案3】:

    我遇到了同样的问题,我通过在 Content-Disposition 之前发送 Content-Length 标头来解决它。

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 2019-02-01
      相关资源
      最近更新 更多