PHP Function Reference

PHP flock() Function



The PHP flock() function is used to lock or release a file. The lock is released also by fclose(), or when stream is garbage collected.

Syntax

flock(stream, operation, would_block)

Parameters

stream Required. Specify the file pointer to lock or release. It is typically creating by using fopen() function.
operation Required. Specify what kind of lock to use. Possible values are:
  • LOCK_SH - A shared lock (reader). Allow other processes to access the file.
  • LOCK_EX - An exclusive lock (writer). Prevent other processes from accessing the file.
  • LOCK_UN - Release a lock (shared or exclusive).
It is also possible to add LOCK_NB as a bitmask to one of the above operations, if flock() should not block during the locking attempt.
would_block Optional. Set to 1 to block other processes while locking.

Return Value

Returns true on success or false on failure.

Example: flock() example

Lets assume that we have a file called test.txt. In the example below, the file is opened using 'r+' mode. Then, an exclusive lock is acquired on the file pointer. After writing some content to it, the lock is released.

<?php
//open the file in r+ mode
$fp = fopen("test.txt", "r+");

//acquiring an exclusive lock
if (flock($fp, LOCK_EX)) {
  //truncating the file
  ftruncate($fp, 0);
  
  //writing some content to it
  fwrite($fp, "flock() function example\n");

  //flushing output before releasing the lock
  fflush($fp); 

  //releasing the lock
  flock($fp, LOCK_UN);    
} else {
  echo "Error locking file!";
}

//close the file
fclose($fp);

//displaying the file content
echo file_get_contents("test.txt")."\n";
?>

The output of the above code will be:

flock() function example

Example: flock() using the LOCK_NB option

The example below shows how to use LOCK_NB option on an LOCK_EX operation while using flock() function.

<?php
//open the file in r+ mode
$fp = fopen("test.txt", "r+");

//activating the LOCK_NB option on an LOCK_EX operation
if (flock($fp, LOCK_EX | LOCK_NB)) {
  //truncating the file
  ftruncate($fp, 0);
  
  //writing some content to it
  fwrite($fp, "flock() function with LOCK_NB option\n");

  //flushing output before releasing the lock
  fflush($fp); 

  //releasing the lock
  flock($fp, LOCK_UN);    
} else {
  echo "Error locking file!";
}

//close the file
fclose($fp);

//displaying the file content
echo file_get_contents("test.txt")."\n";
?>

The output of the above code will be:

flock() function with LOCK_NB option

❮ PHP Filesystem Reference