PHP reading shell_exec live output

To read the output of a process, popen() is the way to go. Your script will run in parallel with the program and you can interact with it by reading and writing it’s output/input as if it was a file.

But if you just want to dump it’s result straight to the user you can cut to the chase and use passthru():

echo '<pre>';
passthru($cmd);
echo '</pre>';

If you want to display the output at run time as the program goes, you can do this:

while (@ ob_end_flush()); // end all output buffers if any

$proc = popen($cmd, 'r');
echo '<pre>';
while (!feof($proc))
{
    echo fread($proc, 4096);
    @ flush();
}
echo '</pre>';

This code should run the command and push the output straight to the end user at run time.

Leave a Comment