Check if a file is already locked using flock()?

user849137 picture user849137 · Mar 25, 2012 · Viewed 9.6k times · Source

I have a file I'm writing to, but I need to lock it first (using flock()), to prevent any other script from writing to it. So I have:

$file=fopen($file_p);

if (flock($file, LOCK_EX)) {//lock was successful
    fwrite($file,$write_contents);          
}

But I need to check if it's already locked, to prevent other scripts from writing to it.

How can I do this?

Answer

y o picture y o · May 15, 2013

As described in the docs, use LOCK_NB to make a non-blocking attempt to obtain the lock, and on failure check the $wouldblock argument to see if something else holds the lock.

if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) {
    if ($wouldblock) {
        // something already has a lock
    }
    else {
        // couldn't lock for some other reason
    }
}
else {
    // lock obtained
}