7

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

hakre
  • 193,403
  • 52
  • 435
  • 836
NightHawk
  • 3,633
  • 8
  • 37
  • 56

2 Answers2

2

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

Ass3mbler
  • 3,855
  • 2
  • 20
  • 18
  • Isn't this in effect that the LOCK_EX modifier is doing? – John Parker Jan 13 '11 at 16:47
  • 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 behaviour – Ass3mbler Jan 13 '11 at 16:49
  • Cool - sounds like this is precisely what the OP is after. +1 from me. :-) – John Parker Jan 13 '11 at 16:51
  • That's what SO is all about - the best answers should float to the top. :-) – John Parker Jan 13 '11 at 16:54
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.

John Parker
  • 54,048
  • 11
  • 129
  • 129
  • 1
    You would need to run a `while` and a `sleep` after a `file_exists` check to be able to wait for the unlock – RobertPitt Jan 13 '11 at 16:41
  • What about question #1 ... if I didn't use a lock, what would happen? – NightHawk Jan 13 '11 at 16:42
  • @RobertPitt - Was updating my answer along these lines. Good call on the up-front file_exists check. :-) – John Parker Jan 13 '11 at 16:43
  • @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. – John Parker Jan 13 '11 at 16:44
  • 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 would – RobertPitt Jan 13 '11 at 17:48