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

2

8

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

Hepatitis answered 13/1, 2011 at 16:36 Comment(0)
F
2

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

Fovea answered 13/1, 2011 at 16:45 Comment(4)
Isn't this in effect that the LOCK_EX modifier is doing?Boggle
As the manual says:"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 if the LOCK_EX returns immediately with an error, it's not the same behaviourFovea
Cool - sounds like this is precisely what the OP is after. +1 from me. :-)Boggle
That's what SO is all about - the best answers should float to the top. :-)Boggle
B
1

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.

Boggle answered 13/1, 2011 at 16:39 Comment(5)
You would need to run a while and a sleep after a file_exists check to be able to wait for the unlockGeologize
What about question #1 ... if I didn't use a lock, what would happen?Hepatitis
@Geologize - Was updating my answer along these lines. Good call on the up-front file_exists check. :-)Boggle
@Ryan S It's hard to tell. (And potentially operating system dependent.) The general catch-all is that the file would be in an "unknown state". :-) That said, unless you're writing quite a lot of data (duration wise), it's quite unlikely to occur. You should however code for this case, as above.Boggle
If you tried to access the file via 2 separate processes it would probably throw an error saying unable to open file or something along those lines, ot may just return false like fopen wouldGeologize

© 2022 - 2024 — McMap. All rights reserved.