English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

Usage and example of PHP flock() function

    PHP Filesystem Reference Manual

The flock() function can lock or unlock a file, and returns true on success, false on failure.

Syntax

bool flock ( resource $handle , int $operation [, int &$wouldblock ] )

The flock() function allows us to perform simple reader/Writer model, which can be used almost on all platforms.

Comments and hints

Comment: These locks are only used in the current PHP process. If permissions allow, other processes can modify or delete a PHP-Locked file.
Comment: The flock() function is mandatory on Windows.
Hint: The locking operation can be released by fclose(), and it will be automatically called when the script execution is complete.

Parameters

ParametersDescription
handle
Required. Specify the opened file to lock or unlock.
operation
Required. Specify the type of locking to use.

Possible values:

  • LOCK_SH - Shared lock (reading program). Allows other processes to access the file.

  • LOCK_EX - Exclusive lock (writing program). Prevents other processes from accessing the file.

  • LOCK_UN - Release a shared lock or an exclusive lock

  • LOCK_NB - Avoid blocking other processes in the locked state.

    These locks are only used in the current PHP process, and if permissions allow, other processes can modify or delete PHP-locked files. On Windows, this function is required. We can use the fclose() function to release the locking operation, which can be automatically called when the script execution is complete.

wouldblock
Optional. If set to 1If set, it will block other processes when locking.

Online Example

Example of using the exclusive lock LOCK_EX of fclock:

<?php
   $file = fopen("/PhpProject/sample.txt", "w+");
   //Exclusive lock
   if(flock($file, LOCK_EX)) {
      fwrite($file, "flock function");
      
       // Unlock lock
      flock($file, LOCK_UN);
      echo $file;
   } else {
      echo "An error occurred while locking the file!";
   }
   fclose($file);
?>

PHP Filesystem Reference Manual