PHP flock()Function


PHP Filesystem 参考手册Complete PHP Filesystem Reference Manual

Definition and Usage

The flock() function locks or releases a file.

Returns TRUE on success, or FALSE on failure.

Syntax

flock(file,lock,block)

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

Possible values:

  • LOCK_SH - Shared lock (for reading). Allows other processes to access the file.
  • LOCK_EX - Exclusive lock (for writing). Prevents other processes from accessing the file.
  • LOCK_UN - Releases a shared or exclusive lock
  • LOCK_NB - Prevents blocking other processes when locking.
block Optional. If set to 1, it blocks other processes during locking.


Tips and Notes

Note:These locks are only used within the current PHP process. If permissions permit, other processes can modify or delete a PHP-locked file.

Note:flock() is mandatory on Windows.

Tip:The lock can be released via fclose(), which is automatically called when script execution completes.


Examples

<?php

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

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

fclose($file);
?>


PHP Filesystem 参考手册Complete PHP Filesystem Reference Manual Other Extensions