PHP locking / making sure a given script is only running once at any given time

Asked
Active3 hr before
Viewed126 times

6 Answers

making
90%

I'm trying to write a PHP script that I want to ensure only has a single instance of it running at any given time. All of this talk about different ways of locking, and race conditions, and etc. etc. etc. is giving me the willies. ,When one task ends, the script is responsible to declare his state in this file (eq: success/failure/debug infos, etc), and then remove his PID. This allows from my view to create admins tools and daemons in a simpler way. And use posix_kill() to kill a PID from PHP if necessary.,If you already use a database, create a table, generate known token for that script, put it there, and just remove it after the end of the script. To avoid problems on errors, you can use expiry times. , 1 probably a mysql lock, in that case, so the script can gracefully abort and say "alread in use". using flock and the like would lock the script off from apache itself and probably cause 500 internal errors and whatnot. – Marc B Jan 31 '12 at 17:06

It will throw the error state, if the file lock.txt isn't reachable.

< ? php

$fp = fopen("lock.txt", "r+");

if (!flock($fp, LOCK_EX | LOCK_NB, $blocked)) {
   if ($blocked) {

      // another process holds the lock
      echo "Couldn't get the lock! Other script in run!\n";

   } else {
      // couldn't lock for another reason, e.g. no such file
      echo "Error! Nothing done.";
   }
} else {
   // lock obtained
   ftruncate($fp, 0); // truncate file

   // Your job here 
   echo "Job running!\n";

   // Leave a breathe
   sleep(3);

   fflush($fp); // flush output before releasing the lock
   flock($fp, LOCK_UN); // release the lock

}

fclose($fp); // Empty memory

Example 2, FIFO (First in, first out): we wants the process to wait, for an execution after the queue, if any:

< ? php

$fp = fopen("lock.txt", "r+");

if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
   ftruncate($fp, 0); // truncate file

   // Your job here 
   echo "Job running!\n";

   // Leave a breathe
   sleep(3);

   fflush($fp); // flush output before releasing the lock
   flock($fp, LOCK_UN); // release the lock
}

fclose($fp);
load more v
88%

That message seemed quite wrong, since there was the only one analysis running. I waited a bit, expecting the port to be released with some delay, but that was wrong. Port are a bit more difficult to check than files : netstat helped. And lsof too :, What is static analysis ?, New error messages in PHP 8.1 , Meet us the 7. – 11. Juni at the Online – International PHP Conference 2021

Creating a file that could serve as a lock is a first-idea solution : the first script creates the file, then any subsequent script finds the file and abort operations. It’s a collaborative system.

< ? php

if (file_exists('/tmp/exakat.lock')) {

   $fp = fopen('/tmp/exakat.lock', 'r+');

   doSomething();

   fclose($fp);

   unlink('/tmp/exakat.lock');

} else {

   print« Another script is running»;

}

?
>
load more v
72%

On Windows, if the locking process opens the file a second time, it cannot access the file through this second handle until it unlocks the file. , LOCK_EX to acquire an exclusive lock (writer). , LOCK_UN to release a lock (shared or exclusive). , Assigning another value to stream argument in subsequent code will release the lock.

load more v
65%

The rename file should ideally be named uniquely to the process doing the renaming so as to make sure not 2 processes do the same thing. But this of course does not prevent editing of the same file by more than one person at the same time. But at least the file will be left intact (last edit wins).,An issue you didn't mention that you also need to be careful of is race conditions where two instances of your script are running at the nearly the same time, for example this order of occurrences:,You have a script that reads the file, changes some of the strings within the document (not just appending but also removing and modifying some lines) and then overwrites all the data with the new data., Idiom or phrase for expressing one's skill/talent has not decayed

Step 3) & 4) would then become this:

$tempfile = uniqid(microtime(true)); // make sure we have a unique name
file_put_contents($tempFile); // write temp file
rename($tempfile, 'original.txt'); // ideally on the same filesystem
load more v
75%

It should be noted that flashdata variables are regular session vars, only marked in a specific way under the ‘__ci_vars’ key (please don’t touch that one, you’ve been warned).,Similarly to flashdata, tempdata variables are regular session vars that are marked in a specific way under the ‘__ci_vars’ key (again, don’t touch that one).,CodeIgniter supports “flashdata”, or session data that will only be available for the next request, and is then automatically cleared.,If you find that you need to preserve a flashdata variable through an additional request, you can do so using the keep_flashdata() method. You can either pass a single item or an array of flashdata items to keep.

$this - > load - > library('session');
load more v
40%

More than one process can hold an exclusive flock on a given file if the exclusive lock was duplicated across a later fork. This simplifies coding for network servers and helps prevent race conditions, but can be confusing to the unaware. ,When using lock files, care must be taken to ensure that operations are atomic. To obtain a lock, the process must verify that the lock file does not exist and then create it, whilst preventing another process from creating it in the meantime. Various methods to do this include: ,Preservation of the lock status on open file descriptors passed to another process using a Unix domain socket is implementation dependent. ,File locking is a mechanism that restricts access to a computer file, or to a region of a file, by allowing only one user or process to modify or delete it at a specific time and to prevent reading of the file while it's being modified or deleted.

Improper error-handling in an application program can lead to a scenario where a file is locked (either using "share" access or with byte-range file locking) and cannot be accessed by other applications. If so, the user may be able to restore file access by manually terminating the malfunctioning program. This is typically done through the Task Manager utility.

The sharing mode (dwShareMode) parameter of the CreateFile[2] function (used to open files) determines file-sharing. The sharing mode can be specified to allow sharing the file for read, write, or delete access, or any combination of these. Subsequent attempts to open the file must be compatible with all previously granted sharing-access to the file. When the file is closed, sharing-access restrictions are adjusted to remove the restrictions imposed by that specific file open.

CreateFile
load more v

Other "making-undefined" queries related to "PHP locking / making sure a given script is only running once at any given time"