PHP

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().

flock($fp, LOCK_UN);

Using file_put_contents() with a File Lock

<?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 coding, this time using an exclusive lock.

by BrainBellupdated
Advertisement: