Latest web development tutorials

PHP flock () function

PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual

Definition and Usage

flock () function to lock or unlock the file.

If successful, the function returns TRUE. If it fails, it returns FALSE.

grammar

flock(file,lock,block)

参数 描述
file 必需。规定要锁定或释放的已打开的文件。
lock 必需。规定要使用哪种锁定类型。

可能的值:

  • LOCK_SH - 共享锁定(读取的程序)。允许其他进程访问该文件。
  • LOCK_EX - 独占锁定(写入的程序)。防止其他进程访问该文件。
  • LOCK_UN - 释放一个共享锁定或独占锁定
  • LOCK_NB - 锁定的情况下避免阻塞其他进程。
block 可选。若设置为 1,则当进行锁定时阻塞其他进程。


Tips and Notes

Note: Use only locks in the current PHP process.If permissions allow, other processes can modify or delete a PHP-locked files.

Note: flock () is mandatory under Windows.

Tip: You can () to release the lock operation by fclose, will automatically call the script 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 Reference Manual Complete PHP Filesystem Reference Manual