January 15, 2008 3:25 PM
PHP has a file locking function flock() that can be used to lock access to a file. But that function has a limitation: it requires the file to be present for the file locking to succeed. This means that if multiple web requests happen simultaneously and the file doesn't exist, you need additional code to guarantee that the file doesn't get overwritten.
This forum post highlights and presents solutions for the issue. The idea is that you can have a global always existing file and use that for locking only. PHP provides semaphore support, but this is not available on windows. In the "user contributed notes" section of the semaphore manual page, there's a mutex class implementation that uses file locking on windows and semaphores on linux / unix. Ideally, production level PHP code will not depend upon file writing, but the availability of something like a mutex is useful to know about.
I personally used flock() without being aware of the file existence problem. This led to a significant increase on server load and upset the system administrator because the code assumed it would be a critical section irrespective of the number of simultaneous hits. I used an always existing file as a global mutex and the problem was solved.
In short, beware of using
flock() in PHP without understanding it's