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:
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.
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);
Note:
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!