PHP General Question concerning memory

I’m learning about opening files and directories and working within them and had a question about the following block of code. Specifically about the fclose() function.

Am I correct in my theory?

The variable $fh has stored information about the file I want to open and the mode of opening it. Then the variable $data gathers the same as well as additional information, provided by the parameters of the fread() function into it’s memory block. Now, we have two blocks of memory with duplicate information, one block of which is no longer needed i.e. the $fh variable. Therefore it is okay to clear that memory before we echo out the information stored in the variable $data.


// set file to read
$file = 'c:/wamp/www/php/php_theory.txt' or die('Could not open file!');
// open file
$fh = fopen($file, 'r') or die('Could not open file!');
// read file contents
$data = fread($fh, filesize($file)) or die('Could not read file!');
// close file
// print file contents
echo $data;


You can just use

echo file_get_contents($file);

I don’t believe it works that way. fopen() returns a “resource” (i.e. it “points” to the file). But it does not contain any duplicate information.

If you are concerned about memory, you should look into clearstatcache() however. Several filesystem functions store results in memory, filesize() is one of them.

As a rule of thumb, I do “first in last out”. In other words if I open in the order ABC I close in the order CBA. Then when I’m sure I’m done, I clearstatcache().

I don’t think that you should be worried about memory in such cases and AFAIK there will not be any duplicate value since fopen returns resource. See clearstatcache() for some flushing/clearing cache state.
Ahh… (Got late to press the button :)) Better described by Mittineague

conceptually, fopen() creates a cursor for the data in a file. Kinda like the blinking cursor in a text editor.

fread() reads data starting from the cursors current position.

This is way over simplified, and there’s a lot more to it.

Thanks for the reply everyone. Very helpful info.