PHP flock() alternative

Matty picture Matty · Aug 6, 2011 · Viewed 7.5k times · Source

PHP's documentation page for flock() indicates that it's not safe to use under IIS. If I can't rely on flock under all circumstances, is there another way I could safely achieve the same thing?

Answer

hakre picture hakre · Aug 6, 2011

There is no alternative available to safely achieve the same under all imaginary possible circumstances. That's by design of computer systems and the job is not trivial for cross-platform code.

If you need to make safe use of flock(), document the requirements for your application instead.

Alternatively you can create your own locking mechanism, however you must ensure it's atomic. That means, you must test for the lock and if it does not exists, establish the lock while you need to ensure that nothing else can acquire the lock in-between.

This can be done by creating a lock-file representing the lock but only if it does not exists. Unfortunately, PHP does not offer such a function to create a file in such a way.

Alternatively you can create a directory with mkdir() and work with the result because it will return true when the directory was created and false if it already existed.