【问题标题】:php rendering large zip file - memory limit reachedphp 渲染大型 zip 文件 - 达到内存限制
【发布时间】:2011-09-11 02:12:12
【问题描述】:

我尝试在 php.ini 中渲染一个 zip 文件。 代码:

header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');

下载的文件,只有几个字节。这是一条错误消息:

<br /> <b>Fatal error</b>: Allowed memory size of 16777216 bytes exhausted (tried to allocate 41908867 bytes) in <b>/var/www/common_index/main.php</b> on line <b>217</b><br />

我不想增加 php.ini 中的 memory_limit。有哪些替代方法可以在不修改全局设置的情况下正确呈现大型 zip 文件?

【问题讨论】:

  • 压缩包从哪里来?从磁盘还是动态创建?基本的解决方案是流式传输数据,这样您就不会同时将其全部保存在内存中。
  • 你用什么函数来转储文件?你看过readfile()吗? php.net/readfile

标签: php zip rendering memory-limit


【解决方案1】:

流式传输下载,因此不会占用内存。 小例子:

$handle = fopen("exampe.zip", "rb");
while (!feof($handle)) {
    echo fread($handle, 1024);
    flush();
}
fclose($handle);

添加正确的输出标题以供下载,您应该可以解决问题。

【讨论】:

    【解决方案2】:

    PHP 实际上提供了一种简单的方法,可以将二进制文件直接输出到 Apache,而无需先通过 readfile() 函数将其存储在内存中:

    header('Content-Type: application/zip');
    header('Content-Length: ' . filesize($file));
    header('Content-Disposition: attachment; filename="file.zip"');
    readfile('file.zip');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2017-12-06
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 2011-08-12
      • 2018-11-16
      相关资源
      最近更新 更多