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//  w w  w.  j  ava2 s.  c o m
      $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//w ww.j av a2s  .c  om

$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);
?>




















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions