file_put_contents and file_get_contents exhaust memory size

Borut Flis picture Borut Flis · Feb 5, 2013 · Viewed 11.5k times · Source

I have some simple trying to write from one file to another.

$content=file_get_contents("C:\Users\Borut\Desktop\sql_PW1\mm_ads (1).sql");
file_put_contents("C:\Users\Borut\Desktop\sql_PW1\New", $content);

The file which I read is about 80M big, the memory limit in php is 128M, but I get an error:

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

So the memory is exhausted even though the memory I am trying to allocate is actually smaller?? I can make this work by increasing the memory limit, but I want to know why it doesnt work with this limit.

Answer

Colin M picture Colin M · Feb 5, 2013

The amount that it shows you in tried to allocate xxxx bytes is the amount over and above the memory limit in PHP. This means you have exhausted your 128MB while you were trying to allocate an additional ~80MB.

Even if you can fit the file into memory, when you know the file is going to be that large, it will be a lot better for you to use a combination of fopen/fread/fwrite/fclose.

I assume that you're going more than just reading the contents and writing it to another file, though, right? Because if that's all you need, you can just use the copy function.