Home > Backend Development > PHP Tutorial > How Can I Get Live Updates from PHP Shell Command Execution?

How Can I Get Live Updates from PHP Shell Command Execution?

DDD
Release: 2024-12-01 04:36:16
Original
813 people have browsed it

How Can I Get Live Updates from PHP Shell Command Execution?

PHP Shell Output with Live Updates

PHP provides several functions for executing shell commands, including shell_exec, exec, system, and passthru. However, these functions typically wait until the command is complete before displaying the results. If you wish to view the command's live output during execution, consider the following alternatives:

Option 1: Using popen() for Parallel Execution

The popen() function opens a pipe between your PHP script and a separate process running the shell command. This allows your script to interact with the process, reading its output in real-time.

<?php
$cmd = 'ping -c 10 127.0.0.1';
$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 runs the ping command and displays its output as it becomes available.

Option 2: Using passthru() for Live Output

The passthru() function directly sends the command's output to the user's browser, allowing you to skip the live updates and show the results as they come.

<?php
echo '<pre class="brush:php;toolbar:false">';
passthru($cmd);
echo '
'; ?>
Copy after login

Optimization Tips:

  • Disable session buffering by calling session_write_close() to prevent it from interfering with parallel execution.
  • Set the header "X-Accel-Buffering: no" if your server is behind an nginx gateway to prevent nginx from disrupting the live output.

By using these techniques, you can enable live updates of shell command output in your PHP scripts, enhancing the user experience and providing real-time insights into the command's execution.

The above is the detailed content of How Can I Get Live Updates from PHP Shell Command Execution?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template