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

删除回忆录丶 提交于 2019-12-05 15:55:01

问题


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 (or script) is also writing to the same file at the same time.

The PHP manual says it will return a falsy value if unsuccessful.

If it cannot obtain a lock on the file, will it fail or keep trying until it can? If it does fail when no lock can be obtained, what would be the best way to go about ensuring the data is written?

Perhaps looping the function in a while loop until it does not return false (cringe) or simply providing the user (website visiter) with some kind of GUI requesting they try again?


回答1:


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.




回答2:


If the function fails to get the lock for the file then it will return an error you can use.

if ($result === false) { print "failed to lock"; }

Now if you want to try to get a the lock a few times just use a loop to keep trying to write to the file.



来源:https://stackoverflow.com/questions/9009058/how-can-i-use-file-put-contents-with-file-append-lock-ex-safety

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!