Testuser075
Testuser075

Reputation: 77

Memory size exhausted (File smaller than my MEMORY_LIMIT)

I'm stuck with an annoying problem which is the title of this topic. I'm trying to read a MP4 format file (which is 69,5 MB(s). A total of 72 899 060 byte(s)) but keep receiving this error. Before reading this file i'm requesting the current usage of the memory with the function memory_get_usage(). Mentioning there is only 3 MB used of a total scale of 128 MB (which is my memory_limit in PHP.ini).

This is the exact error message i'm currently receiving:

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

The function used in order to 'read' this file is file_get_contents(), which simply just retrieves the content of the given path / file.

Sample of the code / 'function':

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

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

I don't understand how we went up from using 3 MB to needing eventually 198 MB. Any ideas?

Upvotes: 1

Views: 1336

Answers (2)

lulyon
lulyon

Reputation: 7265

By file_get_contents($tmpItem); you get more than mypath/tofile/myfile.mp4 equivalent size memory allocated(How can you "get file content" without loading it to the memory?!), which is enough to explain the up-going of the memory.

Upvotes: 1

Daniel W.
Daniel W.

Reputation: 32350

PHP will allocated more memory than it actually uses. Upon trying to allocate more, it fails. Try memory_get_usage(true); to get to see the allocated (reserved) memory instead of the actually used memory.

If you want to work with the contents of the file, you gonna need way more memory, like a few gigabytes probably.

If you simply want to zip the video, you can do this by system calls without using any memory (assuming GNU Linux + zip installed):

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

Upvotes: 0

Related Questions