1

I have a php file which runs a command on linux using shell_exec(). This command takes some time to complete and at each stage prints something out. I want php to echo every line that is printed by command at the moment it is printed.

I found out using ob_flush() and flush(), it is possible to make such chunked http responses, but I can't echo lines as they are printed, because shell_exec() waits until the command is finished and then returns the output. This way, lines are being echoed when command terminates all at once.

I believe I should avoid using shell_exec() for such purpose. How else can I achieve this?

mehrmoudi
  • 1,096
  • 1
  • 11
  • 22
  • not possible using shell_exec, it is possible with proc_open –  Nov 15 '14 at 21:47
  • I would appreciate it if you could tell me in an answer how can I do it. – mehrmoudi Nov 15 '14 at 21:49
  • possible duplicate of [Run process with realtime output in PHP](http://stackoverflow.com/questions/1281140/run-process-with-realtime-output-in-php) –  Nov 15 '14 at 21:59

2 Answers2

2
<?php
$cmd = "ping www.google.com";

$descriptorspec = array(
   0 => array("pipe", "r"),   // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),   // stdout is a pipe that the child will write to
   2 => array("pipe", "w")    // stderr is a pipe that the child will write to
);
flush();
$process = proc_open($cmd, $descriptorspec, $pipes, realpath('./'), array());
echo "<pre>";
if (is_resource($process)) {
    while ($s = fgets($pipes[1])) {
        print $s;
        flush();
    }
}
echo "</pre>";

Source

Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
0

You need to flush the output buffer in order to get it printed immediately:

echo "hello world\n";
flush();

Check the documention of flush()

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • OOps .. Didn't read the question carefully enough. You are already using `flush()`. But `flush()` should work! .. Do you pipe the command into another command? – hek2mgl Nov 15 '14 at 21:35
  • You certainly didn't read the question carefully. I edited it to better convey what I mean. I hope it's clear. – mehrmoudi Nov 15 '14 at 21:40
  • On Linux try: `shell_exec('stdbuf -o0 command');`. Does it work? – hek2mgl Nov 15 '14 at 21:44
  • Note that programs linked to glibc (or any other libc I assume), behave differently if they run from a terminal or not. If you call them using `shell_exec()` they behave like if they are running in a pipe but not directly in a terminal. If programs are running in a terminal the output is normally line buffered. Meaning you every line of out/input immediately on screen. When a program is not running in a terminal the output gets buffered onto a limit (like 4096 bytes) ... This is what you are experiencing .. On Linux (glibc) you can use `stdbuf` to adjust this buffer size. – hek2mgl Nov 15 '14 at 21:51