In the process of using PHP, we often need to read files, but in order to prevent other processes from reading and modifying files and avoiding conflicts, we must read files before The file is locked when fetching, and then the file is modified until the operation is completed. The flock()
function is used in this process. This article will take you to understand the following. For the first time, let's take a look at the syntax of the block()
function:
flock( resource $handle, int $operation, int $wouldblock = ?)
$handle: file system pointer, typically used by fopen()
Created resource
(resource).
$operation: LOCK_SH
Obtain shared lock (reading program). LOCK_EX
Obtains an exclusive lock (writing program. LOCK_UN
Releases the lock (whether shared or exclusive). If you do not want flock()
to block while locking, then Is LOCK_NB
(not supported on Windows yet).
$wouldblock: If the lock will block (in case of EWOULDBLOCK error code), the optional third The parameter will be set to true
. (Not supported on Windows)
Return value: Returns true
on success, or returns on failure false
.
Code example:
1. Use LOCK_EX
<?php $fp = fopen("exit.txt", "r+"); if (flock($fp, LOCK_EX)) { // 进行排它型锁定 ftruncate($fp, 0); // truncate file fwrite($fp, "Write something here"); fflush($fp); // flush output before releasing the lock flock($fp, LOCK_UN); // 释放锁定 } else { echo "Couldn't get the lock!"; } fclose($fp); ?>
exit.text内容:Write something here
2. Use LOCK_NB
<?php $fp = fopen('exit.txt', 'r+'); /* Activate the LOCK_NB option on an LOCK_EX operation */ if(!flock($fp, LOCK_EX | LOCK_NB)) { echo 'Unable to obtain lock'; exit(-1); } fclose($fp); ?>
Recommended: 《2021 Summary of PHP interview questions (Collection)》《php video tutorial》
The above is the detailed content of Analysis of flock() function in PHP (with code examples). For more information, please follow other related articles on the PHP Chinese website!