Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure I have only one instance of a PHP script running via Apache?

Tags:

php

apache

I have an index.php script that I use as a post-commit URL on a Google Code site. This script clones a directory and builds a project that may take some work. I want to avoid having this script running more than one time in parallel.

Is there a mechanism I can use to avoid executing that script if another one is already in session?

like image 540
Rich Avatar asked Aug 10 '11 22:08

Rich


2 Answers

You can use flock with LOCK_EX to gain an exclusive lock on a file.

E.g.:

<?php
$fp = fopen('/tmp/php-commit.lock', 'r+');
if (!flock($fp, LOCK_EX | LOCK_NB)) {
    exit;
}

// ... do stuff

fclose($fp);
?>

For PHP versions after 5.3.2 you need to manually release the lock using flock($fp, LOCK_UN);

like image 140
Long Ears Avatar answered Oct 13 '22 23:10

Long Ears


Only if you save the state of the running script and check when the script starts if an other script is currently active.

For example to save if a script is running you could do something like this:

$state = file_get_contents('state.txt');

if (!$state) {
   file_put_contents('state.txt', 'RUNNING, started at '.time());

   // Do your stuff here...

   // When your stuff is finished, empty file
   file_put_contents('state.txt', '');
}
like image 39
powtac Avatar answered Oct 13 '22 23:10

powtac