Reputation: 38920
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?
Upvotes: 34
Views: 18422
Reputation: 4752
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.
Upvotes: 12
Reputation: 9857
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.
Upvotes: -2
Reputation: 104050
There are also security implications to leaving file descriptors open: http://cwe.mitre.org/data/definitions/403.html
Your program might execute a program with different privilege levels, and a leaked file descriptor may allow private information to cross a boundary between processes of two different trust levels:
http://osvdb.org/7559
CVE-2006-5397
CVE-2007-5159
CVE-2008-3914
The fun thing with security bugs is that it might be perfectly safe when you write the initial function, but a year or two later might become unsafe due to an innocent-looking change.
Upvotes: 9
Reputation: 4179
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).
Upvotes: 0
Reputation: 8814
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.
Upvotes: 4
Reputation: 6157
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.
Upvotes: 0
Reputation: 8200
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.
Upvotes: 26