Page 1 of 1

Realtime output from external command

Posted: Sun Sep 16, 2007 5:21 am
by jpatokal
So I've written a little PHP wrapper that lets people execute various (non-PHP) programs through the web. Straight from the PHP manual:

Code: Select all

$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
The problem is that, while these programs produce continuous output while running (sometimes for several minutes), PHP waits until the execution is finished and only then barfs out the whole output spew. The user thus doesn't know if the program is still running, hung, or if their network is down! Is there any way to channel the output to screen as it's produced?

Any help would be much appreciated.

Posted: Sun Sep 16, 2007 6:33 am
by volka

Posted: Tue Sep 18, 2007 12:12 pm
by jpatokal
Thanks for the idea, but I've tried that, and it seems to buffer the output in exactly the same way as system(). The page you linked to, however, hinted that popen() would work instead, and based on that I was able to cook up the following beautiful code:

Code: Select all

function unbuffered_exec($cmd) {
  $pipe = popen($cmd, 'r');
  if (!$pipe) {
    print "Command execution failed!";
    return "";
  }
  echo "<pre>";
  while(!feof($pipe)) {
    $line = fread($pipe, 1024);
    echo $line;
    flush();
  }
  echo "</pre>";
}
...which works just fine. Thanks! 8)