Two users write to a file at the same time? (PHP/file_put_contents)

纵饮孤独 提交于 2020-01-01 05:19:11

问题


If I write data to a file via file_put_contents with the FILE_APPEND flag set and two users submit data at the same time, will it append regardless, or is there a chance one entry will be overwritten?

If I set the LOCK_EX flag, will the second submission wait for the first submission to complete, or is the data lost when an exclusive lock can't be obtained?

How does PHP generally handle that? I'm running version 5.2.9. if that matters.

Thanks, Ryan


回答1:


you could also check the flock function to implement proper locking (not based on the while / sleep trick)




回答2:


If you set an exclusive file lock via LOCK_EX, the second script (time-wise) that attempts to write will simply return false from file_put_contents.

i.e.: It won't sit and wait until the file becomes available for writing.

As such, if so required you'll need to program in this behaviour yourself, perhaps by attempting to use file_put_contents a limited number of times (e.g.: 3) with a suitably sized usage of sleep between each attempt.



来源:https://stackoverflow.com/questions/4682533/two-users-write-to-a-file-at-the-same-time-php-file-put-contents

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