PHP callback function for similar exec() every output line real time

php

Solution

You can make your own by just calling the each lines returned from `exec` with a callback. See bellow

function exec_callback($command, $callback){
    $array = array();
    exec($command, $array, $ret);
    if(!empty($array)){
        foreach ($array as $line){
            call_user_func($callback, $line);
        }
    }
}

// example to use
function print_lines($line){
    echo "> $line\n";
}

exec_callback("ls -l /", 'print_lines');

Problem

I was searching for a php function or workaround for that would allow you to make a callback function for every line the execution outputs. The best I could find was proc_open(), but it only allowed me to output per specified byte when calling fgets(), to get the output. If I put the bytes too small in fgets() it breaks one line into multiple lines; too large will delay the callback. Is there a function out there in PHP that allows me to call my callback function, similar to proc_open, per output line? Exec() function is a great example since it can puts each line into an array, but it has no option to give callback as it makes each index.

Original source