Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_put_contents and file_get_contents exhaust memory size

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.

like image 578
Borut Flis Avatar asked Dec 27 '22 10:12

Borut Flis


1 Answers

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.

like image 155
Colin M Avatar answered Jan 13 '23 14:01

Colin M