Example 1 — Write with an Exclusive Lock
Lock a file, write to it, and release the lock again.
<?php
$file = __DIR__ . '/lock_demo.txt';
$fp = fopen($file, 'c');
if (flock($fp, LOCK_EX)) {
ftruncate($fp, 0);
fwrite($fp, 'Saved safely');
fflush($fp);
flock($fp, LOCK_UN);
echo "Written with a lock", PHP_EOL;
}
fclose($fp);
unlink($file); How It Works
- fopen() with the c mode opens the file for writing and creates it if it is missing.
- flock() with LOCK_EX waits until no other script holds a lock, then locks the file.
- ftruncate() clears old content, fwrite() saves the new text, and fflush() pushes it to the disk.
- flock() with LOCK_UN releases the lock so another script can use the file.

