Intermediate LevelPHP 8+
How do you prevent file corruption during concurrent write operations in PHP using flock()?
❓ Interview Prompt: Explain flock() advisory file locking, exclusive locks (LOCK_EX), shared locks (LOCK_SH), and non-blocking locks (LOCK_NB).
When multiple concurrent PHP-FPM worker processes write to the exact same log file or cache file simultaneously, data corruption occurs due to interleaved write streams. 'flock()' provides file locking.
Lock Modes:
•
'LOCK_EX' (Exclusive Lock): For write operations. Only one process can hold an exclusive lock; other processes wait.
•
'LOCK_SH' (Shared Lock): For read operations. Multiple processes can hold shared locks simultaneously.
•
'LOCK_NB' (Non-Blocking): Returns immediately instead of blocking if the lock is held by another process.
Code Implementation Example
php
<?php
$fp = fopen('app_log.txt', 'a');
// Acquire Exclusive Lock (LOCK_EX) before writing
if (flock($fp, LOCK_EX)) {
fwrite($fp, "Concurrent safe log entry at " . date('Y-m-d H:i:s') . "
");
fflush($fp); // Flush output buffer to disk
flock($fp, LOCK_UN); // Release file lock!
} else {
echo "Could not lock file!";
}
fclose($fp);💡Executing thread-safe file writes using flock() exclusive locks.
🎯 Interview Key Takeaway
Acquire an exclusive lock (flock($fp, LOCK_EX)) before writing to files to prevent concurrent file corruption.
#flock#File Locking#Concurrency#Intermediate
Back to all PHP 8+ Questions→