2

Studying the principles of blocking files, I could not understand why this code works in this way:

<?php
$fh = fopen('test.txt', 'c');
$res = flock($fh, LOCK_SH | LOCK_NB, $wb);
echo("res:$res, wb:$wb<br>");
if ($res)
{
    flock($fh, LOCK_UN);
    $res = flock($fh, LOCK_EX, $wb);
    sleep(5);
    echo("res2:$res, wb2:$wb");
    flock($fh, LOCK_UN);
}
fclose($fh);
?>

This code should set an exclusive lock for 5 seconds. At every run. And it does.))
But if you run it more often (for example, once per second) then (until file is locked) all subsequent runs will cause the flock() to return "false". And this also works great! ...until you testing it in SINGLE browser TAB.
And now Try to run this script in different TABS of the browser!
Open the script in several tabs and update them consistently. This triggers an ambiguous script operation. In all tabs flock() returns "true"!
However, if you update the first tab twice, this tab and the rest will show the expected result.
And this is not all strangeness!!!
Add any parameter to the URL of each tab (make different URLs), for example ...?tab=1 ...?tab=2 and etc. Yippee! Now all tabs works fine!
WHY???!!!! I spent several hours checking this on several hostings, but I did not understand why it works this way ((


The question is taken off. Code works perfect.
The reason was that the browser did not IMMEDIATELY send a requests. Add

echo(time().'<br>');

at first line and you will see that moment of script start is shifted.
See same explanation in PHP flock() non-blocking still block why?

It should be noted that this problem does not exist in browser Explorer

0 Answers0