Locking Files


 flock($fp, LOCK_UN); 


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:

  • LOCK_EX Exclusive lock for writing

  • LOCK_NB Nonblocking lock

  • LOCK_SH Shared lock for reading

  • LOCK_UN Releasing a lock

The preceding code contains an updated version of the custom file_put_contents() function from the previous phrase, this time using an exclusive lock.




PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net