How can I use file_put_contents() with FILE_APPEND | LOCK_EX safety?

前端 未结 2 2217
借酒劲吻你
借酒劲吻你 2021-02-19 11:07

I\'m using:

file_put_contents(\"peopleList.txt\", $person, FILE_APPEND | LOCK_EX);

to write to the end of a file and to make sure no one else (

2条回答
  •  伪装坚强ぢ
    2021-02-19 12:03

    Actually, my previous answer was a bit out of date. flock() blocks until the requested lock is acquired:

    PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). By default, this function will block until the requested lock is acquired; this may be controlled (on non-Windows platforms) with the LOCK_NB option documented below.

    So since file_get_contents() utilizes it, I'd assume it's the same. That said, be warned that it varies per operating system.

    A bit more importantly, you don't need to lock the file in the scenario you described, for the reasons N.B. already explained. Unless you are using the CLI SAPI, I can't think of a common scenario you should be worried about file locking.

提交回复
热议问题