Home > Backend Development > PHP Tutorial > How Can I Achieve Live Output from PHP Shell Commands?

How Can I Achieve Live Output from PHP Shell Commands?

Mary-Kate Olsen
Release: 2024-12-01 00:41:11
Original
415 people have browsed it

How Can I Achieve Live Output from PHP Shell Commands?

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 '
';
Copy after login

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 '
';
Copy after login

This code opens a pipe to the command, reads its output in chunks, and displays it on the fly.

Useful Information:

  • Call session_write_close() before the loop to prevent session issues.
  • For servers behind nginx, add the header 'X-Accel-Buffering: no' to prevent nginx buffering.
  • Note that live output may be disruptive if your code is running in a loop that also updates the session.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template