The flock Function
The flock
function sets or removes a file lock. Its first parameter is a file pointer obtained via fopen
, the second parameter is the lock type (LOCK_SH, LOCK_EX, or LOCK_UN), and the third optional parameter is a flag for non-blocking operation.
Syntax
flock(resource $handle, int $operation, int &$would_block = null): bool
Example
Locking a file for exclusive access (writing):
<?php
$file = fopen("data.txt", "c+");
if (flock($file, LOCK_EX)) {
ftruncate($file, 0);
fwrite($file, "New data");
flock($file, LOCK_UN);
}
fclose($file);
?>
Example
Shared lock for reading:
<?php
$file = fopen("data.txt", "r");
if (flock($file, LOCK_SH)) {
$content = fread($file, filesize("data.txt"));
flock($file, LOCK_UN);
}
fclose($file);
echo $content;
?>
Example
Non-blocking lock acquisition attempt:
<?php
$file = fopen("data.txt", "c+");
if (flock($file, LOCK_EX | LOCK_NB, $would_block)) {
if ($would_block) {
echo "File is locked by another process";
} else {
fwrite($file, "Data");
flock($file, LOCK_UN);
}
}
fclose($file);
?>
See Also
-
the
fopen
function,
which opens a file -
the
fclose
function,
which closes a file -
the
is_writable
function,
which checks write permissions