Reputation: 74
PHP by default does not have multi threading for our apps, but it is possible, that 2 or more users will click same link in same time or, as in my case, multiple API requests are send in same time.
I have script, that creates quite big file when first user does something.
This is what I have in my code:
if (!file_exists($tmp_file)){
write_file();
}
but sometimes multiple instances of that script are launched in same time in 2 separate Apache threads. In that case, it might happen, that file_exists() will return false, but 0.00001s later, when i'm trying to write that file, it already exists, because it was created by simultaneously running script.
Is there any way to detect such situation and prevent it?
I know I can catch an error and simply not display it to the user, but I prefer not to have any error at all.
Upvotes: 0
Views: 369
Reputation: 27021
You can use fopen with mode 'x', if the file exists, fopen will return false and a warning.
$f = @fopen($tmp_file, 'x');
if($f !== false)
{
fwrite($f, ....);
fclose($f);
}
If you don't even like the warning, use flock
$f = fopen($tmp_file, 'a');
if($f !== false && flock($f, LOCK_EX|LOCK_NB) && ftell($f) === 0)
{
fwrite($f, ....);
fflush($f);
flock($f, LOCK_UN);
}
fclose($f);
Upvotes: 1