内存大小耗尽(文件小于我的MEMORY_LIMIT)

时间:2016-06-24 15:35:23

标签: php file memory file-get-contents readfile

我遇到了一个烦人的问题,这是本主题的标题。我试图读取MP4格式文件(69.5 MB(s)。总共72 899 060字节)但仍然收到此错误。在阅读此文件之前,我使用函数memory_get_usage()请求当前使用内存。提到只有3 MB使用的总规模为128 MB(这是我在PHP.ini中的memory_limit)。

这是我目前正在接收的确切错误消息:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72900608 bytes)

用于阅读'此文件是file_get_contents(),它只是检索给定路径/文件的内容。

代码示例'功能':

echo memory_get_usage() . "<br/>";
$tmpItem = 'mypath/tofile/myfile.mp4';

echo file_get_contents($tmpItem);
echo memory_get_usage() . "<br/>";

我不明白我们如何从使用3 MB到最终需要198 MB。有什么想法吗?

  • 补充:我还试过fopen(),fread(),fclose&amp; ReadFile的()。遗憾的是,所有这些都具有相同的效果。

2 个答案:

答案 0 :(得分:1)

通过file_get_contents($tmpItem);,您可以获得超过mypath/tofile/myfile.mp4等效大小的内存分配(如何“获取文件内容”而不将其加载到内存中?!),这足以说明正在进行的操作记忆。

答案 1 :(得分:0)

PHP将分配比实际使用的内存更多的内存。在尝试分配更多时,它失败了。尝试使用memory_get_usage(true);查看已分配的(保留)内存,而不是实际使用的内存。

如果你想使用文件的内容,你需要更多的内存,比如几千兆字节。

如果您只是想压缩视频,可以通过系统调用来执行此操作,而无需使用任何内存(假设安装了GNU Linux + zip):

<?php
exec('zip -v', $output, $zipFound);

if ($zipFound > 0) {
    throw new \Exception('Error accessing `zip` from command line, is it installed?');
}

exec('zip -q ' . $outputZip . ' ' . $inputMp4, $output, $zipError);

if ($zipError !== 0) {
    throw new \Exception('Error while compressing files: ' . $output);
}
相关问题