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

前端 未结 7 966
囚心锁ツ
囚心锁ツ 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.

提交回复
热议问题