Wednesday, April 20, 2011

Run shell command in background within PHP

In PHP, if you want to run a shell process and don’t want to wait around for it, use shell_exec, and make sure the output of the command is piped to /dev/null.  If you don’t have the output piped to /dev/null, then the shell command won’t be ran in the background.

Example:

<?php
$command = "./runLongScript.sh";
echo "Running: $command\n";
shell_exec("$command > /dev/null &");
echo "After shell_exec\n";
?>


Note that this won’t work if you run this PHP script in a web browser.  This will only work if you run the PHP script on the command line.

No comments: