Run background process from PHP on FastCGI

1.5k Views Asked by At

I know it is possible to create a background PHP process which can be started on demand from another PHP file:

$command = "/usr/bin/php5 -f script.php";
exec( "$command > /dev/null 2>&1 &", $arrOutput);

However this solution works only when PHP is running as mod_php.

Is there any way to do the same on FastCGI?

It seems that on FastCGI the process is started and closed again and again by FastCGI, anyone has experience fixing it?

1

There are 1 best solutions below

0
On

You could setup a cron job? If not, and it must be called within PHP i have once emulated it in a cross platform way without having access to exec() etc by using curl (believe it or not).

Create the .php script and make it public, and add this to the top:

if (isset($_POST['key']) == false || $_POST['key'] != 'your secret key') {
    die(); //request not allowed
}

then from the other PHP file, create a secure (https) curl connection and POST the secret key to it, set a timeout on curl of say 5 seconds (you can also send a http close connection header from the request page) so that the calling script wont freeze if the request takes to long to complete, in your case 30 seconds.

This will do the follow: 1. curl will access the page securely (stops just anyway accessing it in their browser) 2. curl will wait 5 seconds, then close the connection (but BOTH your php scripts will carry on)

It's also compatible regardless of OS internals, shells, etc. You can also tweak the timeouts etc as u see fit.

Not a brilliant solution but hope it works well enough for you.