file locking in php

Since this is an append to the file, the best way would be to aggregate the data and write it to the file in one fwrite(), providing the data to be written is not bigger then the file buffer. Ofcourse you don't always know the size of the buffer, so flock(); is always a good option.


For the record, I worked in a library that does that:

https://github.com/EFTEC/DocumentStoreOne

It allows to CRUD documents by locking the file. I tried 100 concurrent users (100 calls to the PHP script at the same time) and it works.

However, it doesn't use flock but mkdir:

while (!@mkdir("file.lock")) {
   // use the file
   fopen("file"...)
   @rmdir("file.lock")
}

Why?

  1. mkdir is atomic, so the lock is atomic: In a single step, you lock or you don't.
  2. It's faster than flock(). Apparently flock requires several calls to the file system.
  3. flock() depends on the system.
  4. I did a stress test and it worked.

You should put a lock on the file:

$fp = fopen($updateFile, 'w+');
if (flock($fp, LOCK_EX)) {
    fwrite($fp, 'a');
    flock($fp, LOCK_UN);
} else {
    echo 'can\'t lock';
}

fclose($fp);

Tags:

Php

Locking