Codectionary / Developer documentation / PHP

PHP advisory file locks

flock coordinates access to a file among cooperating processes. Hold an exclusive lock across the entire read-modify-write sequence, not just the write call.

Syntax

flock($handle, LOCK_EX); /* work */ flock($handle, LOCK_UN);

Examples

PHP advisory file locks

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
$handle = tmpfile();
if ($handle === false) throw new RuntimeException('Cannot create temporary file');
try {
    if (!flock($handle, LOCK_EX)) throw new RuntimeException('Cannot lock');
    fwrite($handle, '42');
    fflush($handle);
    rewind($handle);
    echo stream_get_contents($handle), PHP_EOL;
    flock($handle, LOCK_UN);
} finally { fclose($handle); }
  1. Output: 42. This self-contained example locks a temporary file; real cooperating processes must open the same persistent file.

Best practices

  • All readers and writers must follow the locking protocol. Check I/O results in production, and avoid opening a shared file in truncating mode before acquiring its lock.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading