phpexecshell-execcommand-line-interfacepassthru

using PHP shell_exec so that the output is "piped" not "dumped"


quick question really.

Consider the following code:

//__/var/test/cli_test.php__
$x = 0;
while ($x < 9){
  print "loop " . str_pad($x, 3, "0", STR_PAD_LEFT) . "\n";
  sleep(1);
  $x++;
}

if I type php /var/test/cli_test.php in the command line I get 9 interspaced-by-time lines.. i.e. 9 positive outputs, one per second. EG: these arrive one at a time, blip blip blip...

loop 000 
loop 001 
loop 002 
loop 003 
loop 004 
loop 005 
loop 006 
loop 007 
loop 008 

now consider a different proposition

//__/var/test/cli_test_shell.php
print shell_exec("php /var/test/cli_test.php");

if I type php /var/test/cli_test_shell.php in the command line I get nothing for 9 seconds then everything arrives.. i.e. 1 BIG output 1 BIG wait. after 9 seconds of nothing EG: wait, wait wait.. nothing THEN DUMP:

loop 000 
loop 001 
loop 002 
loop 003 
loop 004 
loop 005 
loop 006 
loop 007 
loop 008 

how can I alter /var/test/cli_test_shell.php so that the output returns each line on per second


Solution

  • try this:

    $handle = popen('php /var/test/cli_test_shell.php 2>&1', 'r');
    while (!feof($handle)) {
      echo fread($handle, 8192);
    }
    fclose($handle);