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.20
<?php
$root=realpath($_SERVER["DOCUMENT_ROOT"]);
$var=time()."|";
echo $var."<br/>";
$filename=$root."/Testing/Testing/test1.txt";
$myfile=fopen($filename,"a");
fwrite($myfile,$var);
fclose($myfile);
$myfile=fopen($filename,"r");
$contents = fread($myfile, filesize($filename));
echo $contents;
fclose($myfile);
?>
I read that in PHP if multiple users are trying to write to the same file at the same file, there is a chance of data corruption, I of course don't want to have a code that may cause some data corruption over the long run.
I tried to run the above code at almost the same time on my browser to simulate multiple users writing to the same file at the same time, and it produced no errors or any data corruption to the file that is writing to, but I'm still not sure about future data corruptions.
I read that I can use flock to make sure that 2 users can not write to the file at the same time, but since I tested the above code and it produced no data corruption, I'm not sure if I should update my code with flock or just leave it as it is.
My questions are:
1) Is there any chance of the above code corrupting the file that it's writing to?
2) if yes, is using flock will solve this issue? if yes, how should I implement flock in the above code ?
Edit:
I know that this uncertainty can be solved by using a database, but for this case, it's better to use a plain text, so please don't suggest me to use a DB.
thanks in advance.