Run process with realtime output in PHP

Viewed 93872

I am trying to run a process on a web page that will return its output in realtime. For example if I run 'ping' process it should update my page every time it returns a new line (right now, when I use exec(command, output) I am forced to use -c option and wait until process finishes to see the output on my web page). Is it possible to do this in php?

I am also wondering what is a correct way to kill this kind of process when someone is leaving the page. In case of 'ping' process I am still able to see the process running in the system monitor (what makes sense).

12 Answers

why not just pipe the output into a log file and then use that file to return content to the client. not quite real time but perhaps good enough?

I had the same problem only could do it using Symfony Process Components ( https://symfony.com/doc/current/components/process.html )

Quick example:

<?php 

use Symfony\Component\Process\Process;

$process = new Process(['ls', '-lsa']);
$process->run(function ($type, $buffer) {
    if (Process::ERR === $type) {
        echo 'ERR > '.$buffer;
    } else {
        echo 'OUT > '.$buffer;
    }
});

?>
Related