Run process with realtime output in PHP

Run process with realtime output in PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Running Realtime Process Output in PHP

When you use exec() or shell_exec() to run a command like ping, PHP waits for the entire process to finish before returning control to your script. This behavior makes sense from an API perspective, but it breaks the user experience on a web page where you expect continuous updates. The core issue is that standard execution functions buffer output until the process exits or hit specific limits, preventing intermediate lines from appearing in real time.

To achieve realtime updates, you must capture the output stream as it arrives rather than waiting for termination. This usually involves using proc_open() instead of exec(). Unlike exec(), which returns an array of lines only after the command completes, proc_open() gives you direct access to the process's standard input and output streams via file descriptors.

Here is a basic implementation pattern:

$command = 'ping -c 5 localhost'; // Use -c for count if needed
$process = proc_open(
    $command,
    [
        0 => ['pipe', 'r'], // stdin
        1 => ['pipe', 'w'], // stdout
        2 => ['pipe', 'w']  // stderr
    ],
    $pipes
);

if (is_resource($process)) {
    while (!proc_close_status($process) || true) { // Logic to handle streaming
        if ($output = stream_get_contents($pipes[1])) {
            echo htmlspecialchars($output);
            ob_flush();
            flush();
        }
        // Check for process termination or timeout logic here
    }
}

However, there is a critical flaw in the naive approach above. The while loop condition using proc_close_status() won't work as intended because that function returns only when the process actually ends. If you want to stream output continuously without waiting for the end, you need to read from the stdout pipe explicitly inside a loop and check the return status periodically or use a timeout mechanism.

A more robust pattern involves reading small chunks from the stdout pipe repeatedly:

$process = proc_open(
    'ping -c 10 localhost',
    [
        0 => ['pipe', 'r'],
        1 => ['pipe', 'w'],
        2 => ['pipe', 'w']
    ],
    $pipes
);

if ($process !== false) {
    // Set a timeout for the process to run (e.g., 15 seconds)
    $timeout = 15; 
    $startTime = microtime(true);

    while (true) {
        if ($output = stream_get_contents($pipes[1])) {
            echo $output . "\n";
            ob_flush();
            flush();
            
            // Optional: Check if the process has exited
            if (proc_terminate_status($process) !== 0) { 
                break; 
            }
        }

        // Check elapsed time to ensure we don't hang indefinitely
        $elapsed = microtime(true) - $startTime;
        if ($elapsed > $timeout) {
            proc_close($process);
            break;
        }
        
        // Sleep briefly to avoid 100% CPU usage
        usleep(50000); 
    }
}

One of the most common pitfalls in this scenario is not checking whether the process has already terminated. If you simply call stream_get_contents() repeatedly, it will eventually return false or empty string once the buffer is drained and the process exits, potentially causing your script to hang indefinitely if no timeout logic is present. Always monitor proc_status($process) or check the exit code periodically to determine when the external command has finished.

Another significant concern is cleaning up resources when a user leaves the page. In PHP, scripts often run under specific timeouts (commonly 30 or 60 seconds depending on the server configuration). If you are running a long-lived process like ping, the script will eventually timeout and die regardless of whether you explicitly close it. This leaves the external process running in the background, consuming system resources.

To handle this gracefully, you should attach a signal handler or use a timer to terminate the process if the script is about to be killed by the web server. A practical approach involves checking proc_status() for changes that indicate the child process has ended, ensuring you don't leave orphaned processes behind. Additionally, if you are using frameworks like Laravel, consider registering a closure in the event listener system to clean up resources when the request lifecycle ends, although standard PHP scripts require explicit checks within your loop.

If you need to manage these processes more robustly without relying on raw proc_open logic for every scenario, exploring dedicated libraries or integrating with system-level tools designed for process management might offer better stability. For instance, Laravel provides extensive support for queue jobs and background tasks which could abstract away some of this complexity if your use case scales beyond simple realtime output display.

Our network