Why do I need to finish by using the fclose($handle)
function after writing to a file using php? Doesn\'t the program automatically do this when it ends?
There may be unwritten data sitting in the output buffer that doesn't get written until the file is closed. If an error occurs on the final write, you can't tell that the output is incomplete which may cause all sorts of problems much later.
By explicitly calling fclose()
and checking its return value, you have the opportunity to:
or some other way that fits your situation.
This is mention in the comments section of the fclose() manual page.
Not only in PHP, in every language we should close the stream when work is done. In this way we are allowing others to use that file. If we dont close it, other programs may not use it till the program ends completely (in this case page).
Yes, PHP normally closes the file before exiting. But you should always close it manually:
1- It's a good programming practice
2- PHP can exit unexpectedly (for example, an uncaught exception). This may leave the file with something in the queue to be written, or with a lock in it.
Except when the program doesn't end or takes long, it counts towards maximum open file handles in the system. But yes, PHP allows for laziness.
When a file is opened, a lock is placed on it, preventing other processes from using it. fclose()
removes this lock.
$handle
is not an object, just a pointer. So there is no destructor telling it to unlock.
Yes. But, it's good practice to do it yourself. Also, you'll leave the file open during the entire exection of the remainder of the script, which you should avoid. So unless your script finishes execution directly after you're finished writing, you're basically leaving the file open longer than you need to.