I have a website where at the same moment, there can be multiple users writing to the same file at the same time. An example of my code is below.
PHP 5.6
If two scripts attempt to write to a file at the same time. The fopen() function, when called on a file, does not stop that same file from being opened by another script, which means you might find one script reading from a file as another is writing, or, worse, two scripts writing to the same file simultaneously. So it is good to use flock() . You can get more help on http://www.hackingwithphp.com/8/11/0/locking-files-with-flock . For your code you may use flock() as
";
$filename=$root."/Testing/Testing/test1.txt";
$myfile=fopen($filename,"a");
if (flock($myfile, LOCK_EX)) {
fwrite($myfile,$var);
flock($myfile, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock obtained
print "Could not lock $filename!\n";
}
fclose($myfile);
$myfile=fopen($filename,"r");
if (flock($myfile, LOCK_EX)) {
$contents = fread($myfile, filesize($filename));
echo $contents;
flock($myfile, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock obtained
print "Could not lock $filename!\n";
}
fclose($myfile);
?>