The following code triggers an error, though very rarely, when calling file_get_contents
that the file does not exist, even though file_exists
was called only a few statements above.
I believe that the file got deleted, by a cron job, between the time file_exists
was called the error was triggered.
$isRead = self::FILE_READ === $action;
$exists = file_exists($file);
$handle = fopen($file, ($isRead ? 'r' : 'c+'));
if ($handle) {
$locked = flock($handle, ($isRead ? LOCK_SH : LOCK_EX));
if ($locked) {
if ($exists) {
// Sometimes (very rarely) the following line triggers an error that
// $file does not exist
$data = (int)file_get_contents($file);
} else {
$data = 0;
}
if ($isRead) {
// Get Counter
flock($handle, LOCK_UN);
return $data;
}
// Update Counter
if (self::FILE_UPDATE === $action) {
$value += $data;
}
ftruncate($handle, 0);
rewind($handle);
fwrite($handle, $value);
flock($handle, LOCK_UN);
return true;
}
trigger_error("[FileCache] Failed to acquire lock for updating ${file}", E_USER_ERROR);
} else {
trigger_error("[FileCache] Failed to open file ${file}", E_USER_ERROR);
}
Does flock in PHP guarantee that the file will not be modified by any other processes? Or is it limited to the current process?
Also, does unlink
in php honour flock
?