Open In App

How to Run Process with Realtime Output in PHP?

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Running a process with real-time output in PHP involves using the "proc_open" function. This function provides control over the process, allowing interaction and capturing live output and errors. It's particularly useful for executing long-running tasks where immediate feedback is necessary.

prerequisites

Using proc_open() Method

The proc_open function in PHP allows us to execute a command and open file pointers for input and output. And this method gives you a fine gained control over the process and Its I/O streams making It deal for capturing real time output.

Example: This example shows the realtime output by the use of proc_open() method.

PHP
<?php
$descriptorspec = [
    0 => ["pipe", "r"],  // stdin
    1 => ["pipe", "w"],  // stdout
    2 => ["pipe", "w"],  // stderr
];

$process = proc_open('ping -c 4 google.com', $descriptorspec, $pipes);

if (is_resource($process)) {
    while ($line = fgets($pipes[1])) {
        echo $line;
        ob_flush();
        flush();
    }

    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);

    $return_value = proc_close($process);
    echo "The command returned $return_value\n";
}
?>

Output
The command returned 127
1

Next Article
Article Tags :

Similar Reads