I'm using a very simple script where some users data are stored in a text file beside a database because this file needs to be read by a specific process on the system .
The php expire date update code for a line in the following format like this :
U: w w { enddate=2022-10-18 }
The function code goes like this:
$date = "enddate=";
$date .= setExpireDate($duration);
$Read = file($fileDir);
foreach ($Read as $LineNum => $line) {
$LineParts = explode(' ', $line);
if (count($LineParts) == 1) {continue;}
if ($LineParts[1] == $username) {
$LineParts[4] = $date;
$Read[$LineNum] = implode(' ', $LineParts);
break;
}
}
file_put_contents($fileDir, $Read, LOCK_EX);
some users have reported problems , after doing some search i found that the data in the database is updated fine , but the not in the text file as the data is not updated for some users .
as i think it is a file locking problem , that prevents some users under heavy load to write on the file , but the database can handle multiple writes just fine .
So is there anyway to handle the multiple writes on the file at the same time better than this ?
and is there a way to simulate this in php like locking the file by a form submit ?
i tried this :
function lock(){
$fp = fopen("file.txt", "r+");
flock($fp, LOCK_EX);
echo "file is locked <br>";
}
but it is not working at all ,and others can write to the file .
P.S: I know there are a lot of questions about file locking ,but non of the answers did help !
Regards