目录

PHP flock() 函数

❮ PHP 文件系统参考

示例

锁定和释放文件:

<?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);
?>


定义和用法

flock() 函数锁定和释放文件。

语法

flock( file, lock, block)

参数值

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


技术细节

返回值: TRUE 成功,FALSE 失败
PHP 版本: 4.0+
PHP 变更日志: PHP 5.5:添加了对堵塞Windows 上的参数
PHP 5.3:删除了 fclose() 上的自动解锁。现在必须手动解锁

❮ PHP 文件系统参考