PHP reading shell_exec live output

PHP reading shell_exec live output

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Streaming Output from shell_exec in PHP

By default, PHP functions like shell_exec, system, exec, and passthru act as synchronous blockers when handling standard output. They wait for the underlying process to terminate before returning control to your script. This behavior is by design; it ensures that the entire output buffer is available in memory before you attempt to display it. If you run a long-running command like ping or a data processing task, the user has to wait until completion before seeing any results. To achieve live updates, you must bypass this buffering behavior and stream the output directly from the operating system's standard streams to your web response.

Redirecting Standard Output

The core issue in the provided code snippet is that shell_exec captures the entire output of the command into a string variable before returning it.

$cmd = 'ping -c 10 127.0.0.1';
$output = shell_exec($cmd);
echo "<pre>$output</pre>";

In this implementation, PHP spawns the process, reads all lines until exit or a failure occurs, stores them in $output, and then echoes the result. Even if you wrap the echo logic in a loop, shell_exec itself does not yield control between commands because it waits for completion by definition.

To stream output, you must redirect the process's standard output (stdout) to a named pipe or a file descriptor that PHP can read incrementally. On Linux and macOS, the most reliable way to do this is using process substitution or named pipes (FIFOs). However, a simpler approach often used in web contexts involves redirecting stdout to a temporary file and reading it line by line, though true streaming requires careful handling of the process lifecycle.

A more direct method for live updates without intermediate files is to use proc_open. This function allows you to create a process with separate streams for stdin, stdout, and stderr. You can attach these streams to your PHP script using anonymous pipes or file descriptors.

Implementing a Stream with proc_open

The proc_open function provides the flexibility needed to read output in real-time. Here is how you can structure a solution that echoes each line as it arrives:

$cmd = 'ping -c 10 127.0.0.1';

// Create an array of descriptors to capture stdout and stderr
$descriptorspec = [
    0 => ["pipe", "r"],  // Standard input (stdin)
    1 => ["pipe", "w"],  // Standard output (stdout)
    2 => ["pipe", "w"],  // Standard error (stderr)
];

// Open the process
$process = proc_open($cmd, $descriptorspec, $pipes);

if (is_resource($process)) {
    while (!proc_terminate($process) && !feof($pipes[1])) {
        if ($line = fgets($pipes[1])) {
            echo htmlspecialchars($line);
            flush(); // Critical: flushes the output buffer immediately
        }
    }
    
    // Close the process stream
    proc_close($process);
} else {
    echo "Failed to start process.";
}

The critical component here is flush(). PHP's output buffering (OPcache or script-level buffering) collects data until it hits a certain threshold or encounters an EOF. Without flush(), even if you read from the pipe, the data sits in memory until the buffer fills up or the script finishes. Each time a line is printed, flush() forces the data to be sent to the client immediately.

Handling Process Termination and Buffers

One common pitfall when working with streaming output is determining when the process has actually finished. In the example above, the loop checks feof($pipes[1]) to see if the stdout stream is closed by the external process. However, simply relying on proc_terminate without checking the exit status can lead to premature termination of long-running jobs.

You should inspect $processStatus after closing the process to ensure the command exited cleanly:

$exitCode = proc_get_status($process)['exitcode'];
if ($exitCode !== 0) {
    echo "Process exited with code $exitCode";
}

Additionally, be aware of output buffering limits. If your server configuration (php.ini) has a high output_buffering setting, you might need to disable it or ensure that every output operation triggers a flush. In CLI environments or non-web contexts, this mechanism works differently, so ensure your PHP environment is configured for web streaming (e.g., running on Apache/Nginx with mod_php or FastCGI).

Security Considerations

When constructing the command string $cmd, always sanitize inputs. Since shell_exec and proc_open both execute system commands, passing untrusted user input directly into the command can lead to arbitrary code execution vulnerabilities (RCE). Always validate arguments against a whitelist or use parameterized approaches where possible. For instance, if accepting hostnames from users, ensure they contain only valid DNS characters before appending them to the ping command.

Summary of Trade-offs

While shell_exec is convenient for quick tasks, it lacks the granularity required for live feedback. Switching to proc_open adds complexity but grants control over input/output redirection and process management. The trade-off involves increased code verbosity and the necessity to manage process resources manually (opening/closing pipes). If you are building a dashboard that needs constant updates, this streaming approach is essential. However, for simple scripts where immediate feedback isn't required, sticking to shell_exec keeps the logic straightforward and reduces potential points of failure.

Our network