Locking Files
While reading and writing files, you have to take concurrency into mind. What if two processes try to access the file at the same time? To avoid trouble when one process writes while the other one reads, you have to lock the file. This is done using the PHP function flock().
Using file_put_contents() with a File Lock (flock.php; excerpt)
<?php
if (!function_exists('file_put_contents')) {
function file_put_contents($filename, $content)
{
if ($fp = @fopen($filename, 'w') && flock($fp,
LOCK_EX)) {
$result = fwrite($fp, $content);
flock($fp, LOCK_UN);
fclose($fp);
return $result;
} else {
return false;
}
}
}
?>
The first parameter is the file handle; the second one is the desired kind of locking to be used. The following options are available:
The preceding code contains an updated version of the custom file_put_contents() function from the previous phrase, this time using an exclusive lock.
|