flock()

flock() — Portable advisory file locking.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).

Signature

flock(resource $stream, int $operation, int &$would_block = null): bool

Parameters

ParameterTypeWhat it takes
$streamresourceA file system pointer resource that is typically created using fopen().
$operationintoperation is one of the following: LOCK_SH to acquire a shared lock (reader). LOCK_EX to acquire an exclusive lock (writer). LOCK_UN to release a lock (shared or exclusive).
&$would_blockintThe optional third argument is set to 1 if the lock would block (EWOULDBLOCK errno condition).

Return value

Returns true on success or false on failure.

Example

A runnable snippet:

$fp = fopen("/tmp/lock.txt", "r+"); if (flock($fp, LOCK_EX)) { // acquire an exclusive lock ftruncate($fp, 0); // truncate file rewind($fp); fwrite($fp, "Write something here\n"); fflush($fp); // flush output before releasing the lock flock($fp, LOCK_UN); // release the lock } else { echo "Couldn't get the lock!"; } fclose($fp);

All PHP 8.5 built-in functions

Reference card built from the PHP manual page flock() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.