【问题标题】:Proper way to use flush and ob_flush during file download in php在php中文件下载期间使用flush和ob_flush的正确方法
【发布时间】:2019-08-22 13:52:34
【问题描述】:

我正在使用下面的代码下载文件。它使用 flush() 和 ob_flush() 函数。我在此阅读了 brenns10 评论 link

它说使用 flush() 和 ob_flush() 会导致数据进入内存直到显示出来,因此它不好 对于资源有限的服务器。我在共享服务器上。

我需要对此进行解释。我应该在下面的代码中将 flush() 和 ob_flush() 作为它的,还是应该删除它。谢谢

$download_file = '10gb_file.zip';

$chunk = 1024; // 1024 kb/s

if (file_exists($download_file) && is_file($download_file)) {
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . filesize($download_file));
    header('Content-Disposition: filename=' . $download_file);

    $file = fopen($download_file, 'r');

    while(!feof($file)) {
        print fread($file, round($chunk * 1024));
ob_flush();
        flush();
    }

    fclose($file);
}

【问题讨论】:

  • 您是否在此代码之前的任何地方使用ob_start?如果没有,则不需要ob_flush。 flush 也取决于 phps 环境。
  • 问题应该是,这个庞大的网站的文件是否应该首先通过PHP脚本下载,答案是否定的。

标签: php


【解决方案1】:

发送大文件时更好的选择是关闭 PHP 中的缓冲并允许您的 Web 服务器或底层 CGI 层处理它,因为它们更适合处理大输出流,使用诸如写入临时文件之类的技术文件,或将其委托给套接字。

如果您已经在代码的其他地方启动了输出缓冲区,您可能需要先使用 ob_end_clean() 将其关闭。

// removes anything which was in the buffer, as this might corrupt your download
ob_end_clean(); 

// sends the file data to the server without trying to copy it into memory
$fp = fopen($download_file, 'rb');
fpassthru($fp);

【讨论】:

  • 谢谢,ob_end_clean();甚至也适用于 Laravel Excel 等软件包。导出的文件已损坏并添加 ob_end_clean();修好了。
猜你喜欢
  • 1970-01-01
  • 2011-05-27
  • 2011-05-10
  • 2014-11-01
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
相关资源
最近更新 更多