Zach Zach - 4 years ago 189
Bash Question

Running a shell script in the background from PHP

The scenario:


  1. I have a PHP script (accessed via the web) which generates a shell script which needs to continue to run even after the request ends.

  2. I need the output sent to a file on disk (i.e. "./script.sh > run.log")



Every approach I try seems to result in PHP still waiting for the shell script to finish executing. Approaches I've tried:


  1. nohup ./script.sh > run.log &

  2. nohup ./script.sh > run.log 2>&1

  3. nohup ./script.sh > run.log 2>&1 &

  4. ./script.sh &

  5. ./script.sh > run.log 2>&1

  6. ./script.sh > run.log &



I think there's something really obvious I might be missing. Any ideas?

Answer Source

Your number 5 approach is close but you need to combine it with 6 like this

shell_exec("/script.sh > run.log 2>&1 &");

Or redirect to /dev/null like this

shell_exec("/script.sh > /dev/null 2>/dev/null &")

It appears that the PHP development server cannot fork off commands properly. Using a real web server like Apache or NGinx will resolve the issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download