phpmemoryfopenfreadfclose

PHP fclose not freeing up memory


I have a PHP loop whereby I read and process the contents of several files.

<?php
foreach($files as $file)
{
    $f = fopen($file, 'r');
    $content = fread($f, filesize($file));
    import($content);
    fclose($f);
}
?>

However, after several iterations of the loop, I am still getting a memory exhausted error on the fread() line - my understanding was that using fclose() would free up the memory of the resource, but is this not the case?

I have read a number of other questions on the matter and they all referenced using fclose(), which I was already doing. I'm also dumping out memory_get_usage()/memory_get_peak_usage() and they just keep going up until it fails.

Am I misunderstanding how fclose() handles freeing up memory?


Solution

  • <?php
    foreach($files as $file)
    {
        $f = fopen($file, 'r');
        $content = fread($f, filesize($file));
        import($content);
        fclose($f); // this close file
        unset($content); // this free memory allocated to content of file
    }
    ?>