Current Location: Home> Function Categories> flock

flock

Lightweight consultation file locking
Name:flock
Category:File system
Programming Language:php
One-line Description:Lock or release the file.

Definition and usage

flock() function locks or releases a file.

If successful, return true. If it fails, return false.

Example

 <?php

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

// Exclusive locking
if ( flock ( $file , LOCK_EX ) )
  {
  fwrite ( $file , "Write something" ) ;
  // release lock
  flock ( $file , LOCK_UN ) ;
  }
else
  {
  echo "Error locking file!" ;
  }

fclose ( $file ) ;
?>

grammar

 flock ( file , lock , block )
parameter describe
file Required. Specifies the opened file to be locked or released.
lock Required. Specify which lock type to be used.
Block Optional. If set to 1 or true, block other processes when locking is performed.

illustrate

The file for the flock() operation must be an open file pointer.

The lock parameter can be one of the following values:

  • To obtain a shared lock (read program), set lock to LOCK_SH (PHP 4.0.1 previous versions set to 1).
  • To obtain an exclusive lock (write program), set lock to LOCK_EX (set to 2 in previous versions of PHP 4.0.1).
  • To release the lock (whether shared or exclusive), set the lock to LOCK_UN (set to 3 in previous versions of PHP 4.0.1).
  • If you do not want flock() to be blocked during locking, add LOCK_NB to the lock (set to 4 in previous versions of PHP 4.0.1).
Similar Functions
Popular Articles