Categories
josephscott

Fake Fork in PHP

If you aren’t using the Apache module then using pcntl_fork() to fork a PHP process works fine. There are times when it would be really handy to perform a fork in PHP when it is running as an Apache module. There is a way to fake this, sort of.

Instead of forking your PHP script you can exec() another process to run in the background. This obviously isn’t the same as forking, but it is about as close as you can get when running as an Apache module. While reading through the comments on the PHP exec() page I was able to piece together enough information to make execing a background process work. Here’s an example:

exec("/usr/local/bin/myprog 2>/dev/null >&- /dev/null &");

This will execute /usr/local/bin/myprog and redirect STDOUT and STDERR to /dev/null and run the process in the background. You can even pass arguments to your program like this:

$safe_arg["arg_1"] = escapeshellarg($arg_1);
$safe_arg["arg_2"] = escapeshellarg($arg_2);
exec("/usr/local/bin/myprog {$safe_arg["arg_1"]} {$safe_arg["arg_2"]} 2>/dev/null >&- /dev/null &");

Make sure that you escape any data you get from outside your script when using it in exec().