PHP › File Handling & File System Functions
How do file locking mechanisms in PHP, using the flock function, help prevent data corruption when multiple processes might write to the same file concurrently?
IntermediateAnswer
The flock function lets you acquire an exclusive or shared lock on a file before reading from or writing to it, preventing race conditions where multiple processes or requests attempting to write to the same file simultaneously could corrupt its contents or produce inconsistent results, which is especially important for applications that use file based storage for things like counters or logs that might be accessed concurrently by multiple simultaneous requests.
$handle = fopen('counter.txt', 'c+');
if (flock($handle, LOCK_EX)) {
$count = (int) fread($handle, 1024);
ftruncate($handle, 0);
rewind($handle);
fwrite($handle, $count + 1);
flock($handle, LOCK_UN);
}
fclose($handle);Real-world example A simple visit counter stored as a text file uses flock to acquire an exclusive lock before reading and updating the count, preventing two simultaneous visitors from causing the counter to lose an increment due to a race condition.