Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Last active January 10, 2019 22:36
Show Gist options
  • Save MogulChris/bd2ccc21734ef2a2d97e886990e0ff27 to your computer and use it in GitHub Desktop.
Save MogulChris/bd2ccc21734ef2a2d97e886990e0ff27 to your computer and use it in GitHub Desktop.
Ensure a PHP script can only have 1 (or N) instances running at a time
<?php
//Use PHP semaphores to ensure only one (or $max) instances of a script can run at once.
//Semaphores can auto-release if the script crashes, unlike a lock file or database flag which require the script to be functional to release them
//USAGE: Simply include this file at the top of your script. When run, it will die if it finds another instance of itself already running.
// include_once('/path/to/script_run_once.php');
//All we need is a unique 4-digit integer to represent our script. I will hash the current script file path to get this, but you can hard-code $key if you like
//Note $_SERVER['SCRIPT_FILEPATH'] will be the name of the file which has include()-ed script_run_once.php
//Also note with only 9999 possible keys, hash collisions between different strings are unlikely but not impossible
$bignum = hexdec( substr(sha1($_SERVER['SCRIPT_FILENAME']), 0, 15) );
$key = $bignum % 9999;
$max = 1; //max instances
$permissions = 0666;
$autoRelease = 1;
//make or get the semaphore matching $key
$semaphore = sem_get($key, $max, $permissions, $autoRelease);
//Try to acquire the semaphore. This will fail if the semaphore is already acquired by >= $max instances of this script
$sem = sem_acquire($semaphore,true);
if($sem === false) { //already running
die('This script is already running');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment