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

前端 未结 7 855
囚心锁ツ
囚心锁ツ 2020-12-29 03:44

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?

相关标签:
7条回答
  • 2020-12-29 03:53

    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.

    0 讨论(0)
  • 2020-12-29 03:59

    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).

    0 讨论(0)
  • 2020-12-29 04:02

    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.

    0 讨论(0)
  • 2020-12-29 04:02

    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.

    0 讨论(0)
  • 2020-12-29 04:06

    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.

    0 讨论(0)
  • 2020-12-29 04:07

    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.

    0 讨论(0)
提交回复
热议问题