Last active
December 11, 2023 07:01
-
-
Save RWhar/8716f5bc372ec5ec730d to your computer and use it in GitHub Desktop.
Prevent concurrent execution of PHP Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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