Realtime output from external command

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jpatokal
Forum Newbie
Posts: 2
Joined: Sun Sep 16, 2007 5:13 am

Realtime output from external command

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

jpatokal
Forum Newbie
Posts: 2
Joined: Sun Sep 16, 2007 5:13 am

Post 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)
Post Reply