Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need `fclose` after writing to a file in PHP?

Tags:

php

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?

like image 960
locoboy Avatar asked May 18 '11 00:05

locoboy


People also ask

Why is Fclose necessary?

From the Python docs: When you're done with a file, call f. close() to close it and free up any system resources taken up by the open file. This will happen for you when the program exits, but otherwise Python is keeping around resources it no longer needs up to that point.

What is the use of Fclose in PHP?

The fclose() function closes an open file pointer. Note: The file must have been opened by fopen() or fsockopen().

What happens if you don't Fclose?

▪︎when a file was not closed correctly before the program is terminated normally, the operating system will try to close the file. In many cases this can prevent a data loss. ▪︎when a file was not closed correctly, and the programm is terminated unexpectedly by a crash, the loss of data can hardly be prevented.

Why do you need to call the function fclose () to the open resource file?

any file is i/o source, so similar to any source: after you worked with it, release it. fclose function is used for that reason, which allows a the file to be used by another manager/processer etc. Save this answer.


2 Answers

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.

like image 176
dtbarne Avatar answered Sep 24 '22 07:09

dtbarne


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:

  • Retry the operation
  • Unroll the changes
  • Return a failure condition to a calling function
  • Report the problem to the user
  • Document the problem in a log file
  • Return a failure indication to execution environment (such as a command line shell) which may be crucial when used in a tool chain.

or some other way that fits your situation.

This is mention in the comments section of the fclose() manual page.

like image 33
Nisse Engström Avatar answered Sep 21 '22 07:09

Nisse Engström