Live Output with PHP Using popen() and passthru()
PHP's shell_exec() function allows you to execute a command and capture its output. However, displaying the output live during command execution is not possible with shell_exec() or other built-in functions like system(), exec(), or passthru().
For live output, consider using popen() instead. It opens a pipe to a process and allows you to read or write its input/output as if it were a file.
Passthru() for Immediate Output:
If you need to display the output directly to the user without waiting for command completion, you can use passthru():
echo '<pre class="brush:php;toolbar:false">'; passthru($cmd); echo '';
Popen() for Real-Time Output:
To display the output live as the command executes, use popen() and a while loop:
while (@ ob_end_flush()); // end output buffers $proc = popen($cmd, 'r'); echo '<pre class="brush:php;toolbar:false">'; while (!feof($proc)) { echo fread($proc, 4096); @ flush(); } echo '';
This code opens a pipe to the command, reads its output in chunks, and displays it on the fly.
Useful Information:
The above is the detailed content of How Can I Achieve Live Output from PHP Shell Commands?. For more information, please follow other related articles on the PHP Chinese website!