Aryan Aryan - 2 months ago 3
PHP Question

php writing to a file produces output with syntax errors and wrong order of contents

I created a function to store settings to a file (in a readable way) so that the settings can be modified by directly editing the file later on.

I used the method described here.

$data = "<?php return ".var_export($var, true).";";
file_put_contents($filename, $data);

seems to work fine when there are lower no of requests making the changes to the file, but when there are multiple simultaneous requests the file contents are filled with syntax errors or wrong orders of contents and sometimes it remains empty.

I tried using
with third argument LOCK_EX and
after using
but that too resulted in same weird behaviour. What is happening here and how can I correct it ?


The problem here is partial save. Using flock() does not seem to help because it simply sets advisory lock and can be ignored by other processes as described here.

The only option to prevent partial save is to write the data to a temporary file first and then replace the existing with temporary.

I corrected the problem by using the shell command to move and replace the original file.

$data = "<?php return ".var_export($var, true).";";
file_put_contents($filename, $data);
exec("move tempfile ".$filename);  // PHP copy()/rename() seemed to be affected by simultaneous requests.

Those who don't understand what's going on here :

When same file is read and modified simultaneously by multiple processes running in parallel some processes might read the data before another process has finished writing it this sometimes causes wrong/incomplete data to be put into file.