A locking file cache in PHP
The functions “file_get_contents” and “file_put_contents” can be used to implement a file based cache in PHP. Unfortunately the read function is missing a critical feature: support for file locking. Without file locking the function reading the contents may return an empty string (or partial cache content) while the content is being written. Shared and exclusive locks explained If you run the following writer script: <?php // write.php $filename = sys_get_temp_dir().'/test.txt'; $string = 'test'; $file = fopen($filename, 'w'); $lock = flock($file, LOCK_EX); sleep(10); file_put_contents($filename, $string); flock($file, LOCK_UN); fclose($file); And in another tab (at the same time) this reader script: ...