PHP Tutorial - PHP flock() Function






Definition

The flock() function locks or releases a file.

Syntax

PHP flock() Function has the following syntax.

flock(file,lock,block)

Parameter

When you lock a file, we can two options.

  • A read-only lock, thereby sharing access to the file with other processes,
  • An exclusive lock, allowing you to make changes to the file.
ParameterIs RequiredDescription
fileRequired.An open file to lock or release
lockRequired.What kind of lock to use.
blockOptional.Set to 1 to block other processes while locking

Possible values for lock:

  • LOCK_SH - Shared lock (reader).
  • LOCK_EX - Exclusive lock (writer). Prevent other processes from accessing the file
  • LOCK_UN - Release a shared or exclusive lock
  • LOCK_NB - Avoids blocking other processes while locking

The flock() function takes a file handle as its first parameter and a lock operation as its second parameter.





Return

PHP flock() Function returns TRUE on success or FALSE on failure.

Example 1

flock() could be used like this:


<?PHP//from  www  .  j a  v a 2 s .  c  om
      $fp = fopen( $filename,"w"); // open it for WRITING ("w")
      if (flock($fp, LOCK_EX)) {
             // do your file writes here
             flock($fp, LOCK_UN); // unlock the file
      } else {
             // flock() returned false, no lock obtained
             print "Could not lock $filename!\n";
      }
?>




Example 2

Lock a file and write a string to it


<?php/*from   ww w  . j a v  a2s. co m*/

$file = fopen("test.txt","w+");

// exclusive lock
if (flock($file,LOCK_EX)){
  fwrite($file,"java2s.com");
  // release lock
  flock($file,LOCK_UN);
}else{
  echo "Error locking file!";
}

fclose($file);
?>