0

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?

ata
  • 3,398
  • 5
  • 20
  • 31
MattRogowski
  • 726
  • 2
  • 7
  • 22
  • 2
    What does `import($content)` do? Maybe that's what's eating up memory. – Oswald Jan 04 '15 at 13:22
  • Yes, `import()` isn't built-in. Is that function reading all the content from these files and then not freeing it when it's finished? `fclose()` as you have it, will work correctly. – Michael Berkowski Jan 04 '15 at 13:27
  • Hmm, import() just inserts the data to a database, but if I don't call import(), it does get to the end of the foreach loop. What I don't understand though is the content is read with fread() inside the foreach, and just passes it through to import(), so where would I free up the memory? – MattRogowski Jan 04 '15 at 13:35
  • Try using `file_get_contents()` instead of `fread`. – Œlrim Jan 04 '15 at 14:08

1 Answers1

1
<?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
}
?>
Kepi
  • 374
  • 2
  • 7