Mar '17

Forking From Web Process in PHP

As you probably know, for CLI PHP the pcntl_fork command works great for forking off new processes and allowing you to do some fun asynchronous things. However that command is generally not available when running as a web process via an apache handler or similar. I found myself wanting to have some asynchronous actions to be triggered via the web frontend and, after a bit of thought, I came up with the following:

exec('php ' . __FILE__ . ' &> ' . __DIR__ . '/output.txt &');

What we’re doing here is using an exec function to execute our current file in a process, push all output to a file (you can push to /dev/null if you want instead) and run it in the background. Hence the exec command will return immediately, the process will be off and doing its own thing, and you have, in effect, forked your process.

Now I know that if you’re using a full framework then there are better things you can do with queues, events, crons etc, but for a light script this can be pretty helpful.

As an additional quick help, if you want logic to be conditional on the process being executed then you can use the following to tell if you’re in CLI mode or not:

stripos(php_sapi_name(), 'cli') !== false

Leave a Reply