使用PHP下载脚本发送正确的文件大小 [英] Sending correct file size with PHP download script

查看:163
本文介绍了使用PHP下载脚本发送正确的文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 makes a very important comment at the end of the article:


如果您使用Zlib压缩文件,则Content-Length标题中的mod_deflate等将不准确,因此您最终将看到未知大小和未知时间剩下的下载文件。

"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 file:

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下载脚本发送正确的文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆