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?
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
}