How to run a system command in background from PHP

If you are at the command line and want a process to run in the background, you add an & at the end of the command:

sleep 10 && echo "Done!" &

The same approach works from PHP when you need to run a long process without making the user wait:

exec("tar czf /backup/site.tar.gz /var/www > /dev/null 2>&1 &");

The > /dev/null 2>&1 discards output so PHP doesn’t wait for it. The & sends the process to the background.

PHP functions compared

  • exec() — returns last line of output, does not block if output is redirected
  • shell_exec() — returns full output as a string
  • system() — outputs directly to the browser
  • passthru() — for binary output

Using nohup and PIDs

exec("nohup tar czf /backup/site.tar.gz /var/www > /dev/null 2>&1 & echo $!", $output);
$pid = $output[0];

nohup keeps the process alive after PHP exits. The PID lets you monitor or kill it later.

Enjoy!

2 thoughts on “How to run a system command in background from PHP”

  1. A similar command is
    noup [command] &
    that launch a independent process, no need to keep the shell open.

    Never used shell_exec() before. I used to have a permission problem on one hosting once and I solved with a simple queue system (save into db what you need, then a php daemon read the db, execute and delete the record with the info)

Leave a Reply

Your email address will not be published. Required fields are marked *