I have a php script that I want to execute only if another instance of the script is not already running. I have this code:
$lockfile = __DIR__.'/lock.file';
if(file_exists($lockfile) == false)
{
echo 'no lockfile. Job will execute.';
$handle = fopen($lockfile, 'x') or die('Cannot open file: '.$lockfile);
$data = 'This is the lockfile';
fwrite($handle, $data);
fclose($lockfile);
createLinks();
unlink($lockfile);
}
else
{
echo 'Lockfile present, job will not execute. Please try again later';
}
But it does not correctly check if the file exists. If I call the script with my browser, the lock.file will be created correctly (I see it with ftp) and then delete it. However, I can still run the script several times at the same time. If I create a lock.file with ftp, it does not execute the script. I searched for hours now, what could it be? Maybe I'm stupid, but I think this should work, right?
Edit: Jep, the herd did it. Thank you so much! Final code:
$lockfile = __DIR__.'/lock.file';
$handle = fopen($lockfile, "x");
if(flock($handle, LOCK_EX))
{
echo 'no lockfile. Job will execute.';
$data = 'This is the lockfile';
fwrite($handle, $data);
createLinks();
fclose($lockfile);
unlink($lockfile);
}
else
{
echo 'Lockfile present, job will not execute. Please try again later';
}
source
share