How to run a system command in background from PHP

This post is over 3 years old, so please keep in mind that some of its content might not be relevant anymore.

If you are at the command line (eg: bash) and want a command to run in background you simply add an “&” at the end of the command, eg:

sleep 10 && echo "Done!" &

This lets you free to do whatever you want at the command line while the other process runs in background.
Now, let’s suppose you want to do something similar with a script/program called from a PHP web page.

When a website user has to interact with the file system (eg creating a “tar gz” of a directory), I don’t want them to wait for the “tar” command to finish (and maybe even getting a timeout), I want to fork the “tar” in background and reload the web page straight away.
To do this, adding the “&” at the end is not enough because the standard output and standard error would keep the PHP script waiting.
To avoid that, the standard output needs to be piped to “/dev/null” (“>/dev/null”) and the standard error to the standard output (“2>&1”).

From PHP, we would then be running the command as:

shell_exec('sleep 10 && echo "Done" >/dev/null 2>&1 &');

If you load a web page containing this code, it would load immediately as the “sleep 10” runs in background.
In the example of the “tar gz” directory mentioned above, you can notify the user when the directory is ready…

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 *