PHP Reference ยท Files and I/O
PHP flock() function
Reference for PHP flock(): shared and exclusive advisory locks, LOCK_NB, releasing locks, a safe read-modify-write counter pattern and common mistakes.
The flock() function places an advisory lock on an open file. When two scripts (or two web requests) update the same file at the same moment, their writes can interleave or overwrite each other. A lock makes them take turns.
A lock is advisory: it only works when every process that touches the file also calls flock(). A program that ignores locks can still read and write the file freely.
<?php $h = fopen('counter.txt', 'c+'); if (flock($h, LOCK_EX)) { // exclusive access here flock($h, LOCK_UN); } fclose($h);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
flock(resource $stream, int $operation, int &$would_block = null): bool
| Name | Description |
|---|---|
$stream |
An open file handle, for example from fopen(). |
$operation |
LOCK_SH (shared, for readers), LOCK_EX (exclusive, for writers) or LOCK_UN (release). Add LOCK_NB with ` |
$would_block |
Optional. Set to 1 if the lock could not be taken because another process holds it (only meaningful with LOCK_NB). |
Return value: true on success, false on failure.
Errors / Exceptions: a ValueError is thrown if $operation is not a valid combination; invalid handles raise a TypeError.
Usage notes
- Many readers or one writer. Any number of processes may hold
LOCK_SHat once;LOCK_EXwaits until all other locks are gone and then excludes everyone. - Lock before you read when you intend to write the result back. Locking only around the write still loses updates.
- Never open with
'w'and then lock.'w'truncates the file before the lock is taken. Use'c'or'c+', lock, then callftruncate()yourself. - Flush before unlocking. Call
fflush()so buffered data is written while you still hold the lock. - Locks end when you call
LOCK_UN, when the handle is closed, or when the script ends. Closing the handle is the usual way to release. - Not a database. Locks are not guaranteed on some network file systems, and they do not give you transactions. For shared state with many writers, use a database.
LOCK_EXinfile_put_contents()is a shortcut for one-shot writes:file_put_contents($p, $data, LOCK_EX).- Deadlocks are possible if two scripts lock two files in opposite order. Always lock files in a fixed order.
- Windows locks are mandatory rather than advisory in some cases and
LOCK_NBbehaves slightly differently. Test on your target system.