Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

flags

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

like image 287
NightHawk Avatar asked Jan 13 '11 16:01

NightHawk


2 Answers

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

like image 95
Ass3mbler Avatar answered Nov 09 '22 13:11

Ass3mbler


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.

like image 31
John Parker Avatar answered Nov 09 '22 11:11

John Parker