How to run a linux terminal command with PHP non-blocking?

linux, php

Solution

HACK ALERT, but if you don't want to background it (say you need to do something with the result) and don't care when it finishes you could put the command in the destructor method of an object. Note that that while the user will get their response and be free to request another page, the process won't be freed from Apache or PHP-fpm until it's done.

class someClass{

      function __destruct(){   
           exec('du -hs');
       }     
}

NOTE: the robust way to process tasks in the background would be to use a message queue and job service handler build out with gearman, rabbitMQ, or such.

Problem

Suppose I'd like to run a server side command with PHP on form submit via my webpage. The command is du -hs which could take several minutes to complete. Could I use exec() or shell_exec() in a way so that the webpage reloads immediately and doesn't wait for the output of the command? An example would be great! Thanks! ``` <?php exec('du -hs'); ?> ```

Original source

Related problems