I want to read a file into a string, modify the content and write back the processed string to the file. Also, another request to the server might start too early and try to write the same file before the first is through - that must NEVER happen (so far im using flock) - it would be even better, if the script would be blocking until the lock is released.
Here is some sort of incomplete approach
$h = fopen($fp, 'a+');
flock($h, LOCK_EX);
$oTxt = '';
while (!feof($file)) {
$oTxt .= fread($h, 8192);
}
rewind($h);
ftruncate($h, 0)
fwrite($h, ); // process contents and write it back
flock($h, LOCK_UN);
fclose($h);
Note: This question is very similar to What's the best way to read from and then overwrite file contents in php? (in my case its a json file i want to decode, insert or edit some node, then encode it again) but its not a duplicate.
You can replace the while
loop with a single call to stream_get_contents
. And you should use mode r+
to read and write the file; a+
will position the stream at the end of the file when you start, so there won't be anything to read.
$h = fopen($fp, 'r+');
flock($h, LOCK_EX);
$oTxt = stream_get_contents($h);
// Process contents
rewind($h);
ftruncate($h, 0);
fwrite($h, $oTxt);
flock($h, LOCK_UN);
fclose($h);