PHP flock() Function

The flock() function locks or releases a file.This function returns TRUE on success or FALSE on failure.

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

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).

On versions of PHP before 5.3.2, the lock is released also by fclose() (which is also called automatically when script finished).

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). By default, this function will block until the requested lock is acquired; this may be controlled with the LOCK_NB option documented below.

Example -

Example -

ParameterDescription
fileRequired. Specifies an open file to lock or release
lockRequired. Specifies what kind of lock to use.
Possible values :-
  • LOCK_SH - Shared lock (reader). Allow other processes to access the file
  • LOCK_EX - Exclusive lock.Prevent other processes from accessing file
  • LOCK_UN - Release a shared or exclusive lock
  • LOCK_NB - Avoids blocking other processes while locking
  • blockOptional. Set to 1 to block other processes while locking