Executing external programs in PHP isn’t a very big surprise – a decent number of articles have been written about the topic, including one I’ve written. However, getting a process to fire off in the background and carry along on its merry way while the web page continues doing its thing is a bit tricker.
You’ll want to use the system shell’s
& operator, which means we’ll use the
If you tried something like:
you’d probably see that the program fired off okay, but that the web page locks up until the program has finished running.
The trick, it seems, is to make sure there is no output from the program. So, be sure to redirect any output to
/dev/null, as follows:
shell_exec("/path/to/program > /dev/null &");
And now you can fire off programs willy-nilly. Just be be aware of the security implications of this:
- Be outrageously careful if you let user input factor into commands (I never do), as they might inject some malicious shell script.
- Be prepared for possible denial-of-service attacks using this functionality: Are you prepared to handle the case where the web page is requested hundreds or thousands of times?
Happy Programming![Read Rest of Article]