Portable advisory file locking
Syntax
flock(resource $stream, int $operation, int &$would_block = null): bool
Parameters
stream
A file system pointer resource that is typically created using fopen().
operation
Name | Description |
---|---|
LOCK_SH | acquire a shared lock (reader) |
LOCK_EX | acquire an exclusive lock (writer) |
LOCK_UN | release a lock (shared or exclusive) |
LOCK_NB | add as a bitmask to one of the above operations if flock() should not block during locking |
would_block
The optional third argument is set to 1 if the lock would block (EWOULDBLOCK errno condition).
Return
Returns true on success or false on failure.
Examples
1 · stream operation · LOCK_SH
<? $filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt'; $mode = 'r'; $stream = fopen($filename, $mode); $operation = LOCK_SH; $return = flock($stream, $operation); if($return) { $length = filesize($filename); $contents = fread($stream, $length); flock($stream, LOCK_UN); echo $contents; } else { echo "could not lock"; } fclose($stream); ?>
Hello
2 · stream operation · LOCK_EX
<? $filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt'; $mode = 'w'; $stream = fopen($filename, $mode); $operation = LOCK_EX; $return = flock($stream, $operation); if($return) { $contents = "Hello"; fwrite($stream, $contents); flock($stream, LOCK_UN); echo $contents; } else { echo "could not lock"; } fclose($stream); ?>
Hello
3 · stream operation · LOCK_NB
<? $filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt'; $mode = 'w'; $stream = fopen($filename, $mode); $operation = LOCK_EX | LOCK_NB; $return = flock($stream, $operation); if($return) { $contents = "Hello"; fwrite($stream, $contents); flock($stream, LOCK_UN); echo $contents; } else { echo "could not lock"; } fclose($stream); ?>
Hello
4 · would_block
<? $filename = $_SERVER['DOCUMENT_ROOT'] . '/assets/txt/file.txt'; $mode = 'w'; $stream = fopen($filename, $mode); $operation = LOCK_EX; $would_block = 1; $return = flock($stream, $operation, $would_block); if($return) { $contents = "Hello"; fwrite($stream, $contents); flock($stream, LOCK_UN); echo $contents; } else { echo "could not lock"; } fclose($stream); ?>
Hello