I've been looking for a way to prevent running a php script simultaneously. So I found a way (on this site) to prevent this. This is where I came with (test file).
Link to found solution on stackoverflow: How to prevent PHP script running more than once?
test.php
echo "started: ".microtime()."<br>";
$lock = $_SERVER['DOCUMENT_ROOT'].'/tmp/test.lock';
$f = fopen($lock, 'x');
if($f === false){
die("\nCan't aquire lock\n");
}else{
// Do processing
echo "Working: ".microtime()."<br>";
sleep(5);
echo "Still working: ".microtime()."<br>";
sleep(5);
echo "Ready: ".microtime()."<br>";
fclose($f);
unlink($lock);
}
When running this script for the first time, the output will be like this:
started: 0.87157000 1389879936
Working: 0.87532100 1389879936
Still working: 0.87542000 1389879941
Ready: 0.87551800 1389879946
Now when I run the same script in the same browser simultaneously, both will be executed, however the second one is executed after the first one. So not simultaneously, but twice. I didn't expect that because it should die if the test.lock file already exists.
So running the script in the same browsers with two tabs, this is the result:
tab1:
started: 0.87157000 1389879936
Working: 0.87532100 1389879936
Still working: 0.87542000 1389879941
Ready: 0.87551800 1389879946
tab2:
started: 0.92684500 1389879946
Working: 0.92911700 1389879946
Still working: 0.92920300 1389879951
Ready: 0.92930400 1389879956
As you can see, the script in the 2e tab is started when the script in the first tab is finished. Isn't that weared?
When I do this with different browsers, the script started as second is terminated, so it works.
browser 1:
started: 0.62890800 1389880056
Working: 0.63861900 1389880056
Still working: 0.63878800 1389880061
Ready: 0.63893300 1389880066
Browser 2:
started: 0.10137700 1389880058
Warning: fopen(/home/users/domain/tmp/test.lock) [function.fopen]: failed to open stream: File exists in /home/users/domain/test.php on line 8
Can't aquire lock
The question
I'm now able to prevent executing the script simultaneous, but how to prevent the second script in the same browser of being executed after the first script is finished!