flock
Locks a file so that two processes do not work with it at once.
Syntax
flock(resource $stream, int $operation, int &$would_block = null): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $stream | resource | An open file. |
| $operation | int | `LOCK_SH` for reading, `LOCK_EX` for writing, `LOCK_UN` to release. |
| $would_block | int | Optional. Set when the lock would have to wait. |
Return value
bool`true` if the lock was acquired.
Examples
A counter protected by a lock:
<?php
$file = sys_get_temp_dir() . '/ref-counter.txt';
file_put_contents($file, '41');
$handle = fopen($file, 'c+');
flock($handle, LOCK_EX);
$count = (int) fread($handle, 20) + 1;
ftruncate($handle, 0);
rewind($handle);
fwrite($handle, (string) $count);
flock($handle, LOCK_UN);
fclose($handle);
echo file_get_contents($file);Output:
42Notes
Without a lock two simultaneous requests read the same value and one of them is lost. For a simple write there is file_put_contents($file, $data, LOCK_EX).
See also
- fopen — Opens a file for reading or writing piece by piece.
- fwrite — Writes a string to an open file.
- file_put_contents — Writes data to a file.
In the tutorial
- Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.