Skip to content

Instantly share code, notes, and snippets.

@hoai
Forked from RWhar/nonConcurrentScript.php
Created December 11, 2023 07:01
Show Gist options
  • Save hoai/c85c2acaf8729d7cf76144dd215ac453 to your computer and use it in GitHub Desktop.
Save hoai/c85c2acaf8729d7cf76144dd215ac453 to your computer and use it in GitHub Desktop.
Prevent concurrent execution of PHP Script
/**
* Creates an exclusive lock
* @param $lockDir Directory to create/access lock file
* @param $lockName Name for lock
* @param $lockHandle Reference to scope var to maintain file handle after lock call completes
* @return bool
* @throws Exception on $lockdir not writable, unable to create file handle, unable to obtain ex_lock
*/
function lock($lockDir, $lockName, &$lockHandle)
{
$lockFileName = $lockName . '.lock';
$lockFullPath = $lockDir . DIRECTORY_SEPARATOR . $lockFileName;
if (!is_writable($lockDir)) {
throw new Exception('Unable to create lock, ' . $lockDir . ' must be writable.');
}
$lockHandle = fopen($lockFullPath, 'w');
if (!$lockHandle) {
throw new Exception('Unable to write lock file: ' .$lockFullPath);
}
if (!flock($lockHandle, LOCK_EX | LOCK_NB)) {
throw new Exception($lockName . ' Currently locked.');
}
return true;
}
/* Test lock() */
$lockDir = __DIR__;
$scriptName = basename(__FILE__, '.php');
$lockHandle = null;
try {
lock($lockDir, $scriptName, $lockHandle);
} catch (Exception $e) {
exit($e->getMessage());
}
echo "$scriptName Script Running...";
sleep(10);
echo "\nScript finished!";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment