Check if a file is already locked using flock()? [duplicate]
Question
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?
Solution
I would check to see if I couldn't obtain a lock on the file, like this:
if (!flock($file, LOCK_EX)) {
throw new Exception(sprintf('Unable to obtain lock on file: %s', $file));
}
fwrite($file, $write_contents);
OTHER TIPS
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
}
Your flock call is the check to see if it's already locked. If it's locked, that if() statement would fail, so you could just throw an else on it with something like:
if (flock($file, LOCK_EX)) {//lock was successful
fwrite($file,$write_contents);
} else {
echo "$file is locked.";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow