PHP flock() Function

❮ PHP Filesystem Reference

Example

Lock and release a file:

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

// exclusive lock
if (flock($file,LOCK_EX)) {
  fwrite($file,"Add some text to the file.");
  fflush($file);
  // release lock
  flock($file,LOCK_UN);
} else {
  echo "Error locking file!";
}
fclose($file);
?>


Definition and Usage

The flock() function locks and releases a file.

Syntax

flock(file, lock, block)

Parameter Values

Parameter Description
file Required. Specifies an open file to lock or release
lock Required. Specifies what kind of lock to use.

Possible values:

  • 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 the lock
  • LOCK_NB - Avoid blocking other processes while locking
block Optional. Set to 1 to block other processes while locking


Technical Details

Return Value: TRUE on success, FALSE on failure
PHP Version: 4.0+
PHP Changelog: PHP 5.5: Added support for the block parameter on Windows
PHP 5.3: Removed automatic unlocking on fclose(). Unlocking must now be done manually

❮ PHP Filesystem Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.