Recently I started to face problems about memory management in PHP. This is something new to me because I never needed to run PHP scripts for long time on background threads. So, now I'm studying the subject and came to the simple script that follows:
function w()
{
$f = fopen('test1.txt', 'w+');
fclose($f);
unset($f);
}
$i = 0;
$max = 5;
echo 'Memory usage:<br><br>';
echo $i . ' - ' . memory_get_usage() . '<br>';
touch('test1.txt');
while(++$i < $max)
{
w();
echo $i . ' - ' . memory_get_usage() . '<br>';
}
It only opens and closes the same file multiple times, and after each close it displays the memory used.
As you can see, even after closing and unset()'ing the handler, the memory doesn't drop. It seems that internally the pointer is still holding memory. I know, they are a few bytes, but even a few bytes can break the script if it is running on a background thread (that's my real purpose).
I tried setting $f = null but it consumes even more memory (I'm not crazy, check for yourself)! And gc_collect_cycles() also didn't work.
So my question is: is there a way to completely free the memory of a file handler?