PHP

Prevent simultaneous calls to a php function

Oct 25, 2019

To prevent many users to trigger a function that must only be run once at a given time, it's possible to use a semaphore to lock the process !

A great way to avoid simultaneous calls to a specific PHP script

$semaphore_key = 8427;		// unique integer key 
$semaphore_max = 1;		// The number of processes that can acquire this semaphore
$semaphore_permissions = 0666;	// Unix style permissions for this semaphore
$semaphore_autorelease = 1;	// Auto release the semaphore if the request shuts down
 
// open a new or get an existing semaphore
$semaphore = sem_get($semaphore_key, $semaphore_max, $semaphore_permissions, $semaphore_autorelease);
if(!$semaphore) 
{
     echo "Failed to get semaphore - sem_get().\n";
     exit();
}

// acquire exclusive control	
sem_acquire($semaphore);


    myPreciousFunction();  //The function that must only be run once

// release exclusive control	
	sem_release($semaphore);

PHP   function   simultaneous