Search code examples
phpfileiofile-put-contents

What happens when two scripts want to write at the same time on a file with LOCK_EX?


What happens if a PHP script wants to:

file_put_contents("testfile", $s, FILE_APPEND | LOCK_EX);

while another script already does the same thing on the same file (with a LOCK_EX too)?

It's unlikely to happen that 2 scripts want to write exactly during the same millisecond (for a < 100 kB file), but let's imagine it happens.

Would the file_put_contents function notice it's locked, wait for say 10ms and then retry, or would the PHP script fail, and the data to be written is lost?


Solution

  • Both processes will call flock() to lock the file before they start writing. The first one will get the lock, the second will wait until the file is unlocked. There's no retrying, it's handled automatically by the OS. The documentation doesn't mention a timeout, so I assume there isn't one.

    The first process will unlock the file as soon as it finishes writing, then the second process will run.

    You generally don't need LOCK_EX if you're using FILE_APPEND. Each call to write() is atomic, and when the file is opened in append mode the filesystem ensures that each process writes at the new end-of-file, not EOF position when the file was opened.