I want to create a simple method to write a string to a log file, and since the file might be written by different web server processes at the same time, file locking is needed for atomicity.
e.g.
function log_to_file($message)
{
$fp = fopen("/tmp/lock.txt", "r+");
while (!flock($fp, LOCK_EX)) {
sleep(1); // Sleep for 1 second and try again
}
fwrite($fp, $message);
fflush($fp);
flock($fp, LOCK_UN); // release the lock
fclose($fp);
}
Any problem with the above code?