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); }- 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