0

I am trying to stream live output from some scripts using PHP. There are numerous questions regarding this on StackOverflow. I have followed these answers:
PHP reading shell_exec live output
Bash script live output executed from PHP
Run process with realtime output in PHP
Live output to a file with PHP exec()?

But, none of them works for me. I am always getting the whole output on command completion. Here is my final code which I have used:

$cmd = "/path/to/command";

$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>";

Platform: Arch Linux with Apache

Puspam
  • 2,137
  • 2
  • 12
  • 35
  • The live process output is a red herring. For your own sanity with debugging, this is the [general code](https://3v4l.org/vukaC) that you want to get working. The problem most likely is that PHP _is_ flushing, however the server executing PHP might be buffering. I would recommend reading through ways to adjust the server in this answer: https://stackoverflow.com/a/4978642/231316 – Chris Haas Jul 25 '22 at 16:57

1 Answers1

0

I was trying to run a Python program as the external command.
I did more research and it turned out that there was output buffering from Python's side, so PHP wasn't getting any output until all the output was sent out by the Python interpreter.
I disabled output buffering in the python command and now it works as expected.

To disable output buffering in python, just add the -u switch: python -u my_prog.py

Puspam
  • 2,137
  • 2
  • 12
  • 35