3

I'm using flock() function to check if another instance of the script is already running by obtaining the lock on a temporary file so next instance should check if the file is not locked otherwise it stops

<?php    
$fp = fopen("/var/tmp/your.lock", "w");
if (!flock($fp, LOCK_EX|LOCK_NB)) { // try to get exclusive lock, non-blocking
    die("Another instance is running");
} 

//my script 
sleep(10);
echo 'completed successfully';

the script works without problem when calling the file twice at the same time from different browsers while it waits if I opened two instances at the same time from the same browser i.e the first call get the lock and the second wait for the lock and not closing

I know there may be other ways to check if a file an instance is already working but most of them will do a thing then undo it and in my use case the script may end any time as it may take long time or exceed memory limit or by any reason

any help ?

Atef
  • 593
  • 1
  • 8
  • 18

2 Answers2

6

The problem was :

calling the same script twice with the same url from the browser will thread via the same process and flock() function non-blocking working on the process layer causing the second script to wait

as example calling example.com/test.php twice will cause the two requests work on the same process wile appending any random variable will create separate process for each single request like

example.com/test.php?rand=1
example.com/test.php?rand=2

works great .

Atef
  • 593
  • 1
  • 8
  • 18
  • I've seen many answers but none of them made this work on win7 wamp like this one! Thank you! – JanBo Jun 29 '13 at 00:17
  • Note, this error has nothing to do with flock(), you'd see the same problem with sleep(100) or any other long-running script. Depending on your browser and/or web server settings, you may be limited to one simultaneous request, or one request per unique URL like you have, or no restrictions at all. – btraas May 20 '20 at 23:42
5

Run the same script from the command line twice. I would be willing to bet it works just fine.

Chances are that your browser is rate limiting connections to the server by only allowing one connection at a time to any given host. The fact that you get different results in different browsers would indicate that it's not a PHP problem, as PHP will perform the same regardless of the browser requesting the page.

Colin M
  • 13,010
  • 3
  • 38
  • 58
  • 1
    You are right , I tried to append a variable like test.php?rand=10 test.php?rand=20 and yes it worked great from the browser. seems that the browser blocked the second request so the solution is to send something different in a var . – Atef Nov 11 '12 at 14:13