Home >Backend Development >PHP Tutorial >php flock function_PHP tutorial
The function of flock in php is to lock the file when operating the file, and it is only available when the lock is cancelled.
The function of flock in php is to lock the file when operating the file, and it is only available when the lock is cancelled.
flock
(PHP 4, PHP 5)
flock - portable advisory file locking
Description
boolean group(resource$process, int$operation[summary&$wouldblock])
flock() allows you to implement a simple reader/writer mode, which can be used on almost all platforms (including most Unix derivatives and even Windows).
The lock is also released by fclose() (also called autocomplete when scripted).
PHP supports portable mode locking in a full file advisory mode (meaning all accessing programs must use the same mode of locking or it won't work).
Parameters
Handle
An open file pointer.
Operation
Do one of the following:
LOCK_SH acquires a shared lock (reader).
LOCK_EX acquired exclusive lock (writer).
LOCK_UN releases the lock (shared or private).
LOCK_NB if you don't want flock() to block while locking. (Not supported on Windows)
wouldblock
The optional third parameter is set to TRUE if locking would block (EWOUULDBLOCK errno condition).
Return value
Returns TRUE or FALSE on success or failure.
Edit
Release Notes
The 4.0.1 constant LOCK_XXX was added. Before that, you have to use 1 LOCK_SH, 2 LOCK_EX, 3 LOCK_UN and 4 LOCK_NB
Example
Example of #1flock()
$fp = fopen("/tmp/lock.txt", "w+");
if (flock($fp, LOCK_EX)) { // do an exclusive lock
fwrite($fp, "Write something here");
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't lock the file !";
}
fclose($fp);
?>