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.
<?php
// 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
fclose($fh);
// print file contents
echo $data;
?>
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.
Edit:
Ahh… (Got late to press the button :)) Better described by Mittineague