Home > Backend Development > PHP Tutorial > How Can I Get Real-Time Output from Shell Commands in PHP?

How Can I Get Real-Time Output from Shell Commands in PHP?

Mary-Kate Olsen
Release: 2024-12-03 20:03:16
Original
320 people have browsed it

How Can I Get Real-Time Output from Shell Commands in PHP?

Real-Time Output with PHP's Shell Execution

Shell execution in PHP, using functions like shell_exec and exec, can be beneficial for interacting with the operating system. However, by default, these functions display the entire output only after the command has completed. This limits the ability to monitor progress or display real-time updates.

Solution: Unleashing the Live Output

To achieve real-time output display, PHP offers two primary options:

  1. popen() for Parallel Interaction:

    popen() allows you to establish a bidirectional communication channel with a child process. This enables you to read and write to the child process as if it were a file. By using a loop and fread(), you can capture the output and display it dynamically.

  2. passthru() for Direct Output:

    For a simpler approach, passthru() can be used to directly print the output of a command to the browser. It provides a convenient way to stream the results without intermediary storage.

Code Example Using popen():

// Ensure flushing of output buffers
while (@ ob_end_flush());

// Open the child process for reading
$proc = popen($cmd, 'r');

echo '<pre class="brush:php;toolbar:false">';

// Keep reading and displaying output until EOF
while (!feof($proc)) {
    echo fread($proc, 4096);
    flush();
}

echo '
'; // Close the process pclose($proc);
Copy after login

Note:

  • Use session_write_close() before the loop if sessions are active to avoid blocking concurrent requests.
  • Set the header header('X-Accel-Buffering: no'); if an Nginxgateway is present to disable buffering.

The above is the detailed content of How Can I Get Real-Time Output from Shell Commands in PHP?. 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