PHP real-time system command output

Throwing some notes here for me to remember on having PHP not buffer the output of a long running process so that it provides realtime output to the browser. I tinkered with SSE options and even AJAX/jQuery, but I finally got this to somewhat work reliably. Note that these notes are tested on PHP 8.1 and Apache 2.4.

.htaccess

This is required to disable buffering at the server level. Make sure to have mod_rewrite enabled.

RewriteRule ^(.*)$ $1 [NS,E=no-gzip:1,E=dont-vary:1]

PHP

<?php
ob_implicit_flush(1);

echo 'Begin', PHP_EOL;


for ($i = 0; $i < 10; $i++) {
    echo $i, PHP_EOL;
    ob_flush();
    flush();

    sleep(1);
}

echo 'Done', PHP_EOL;

A command example using passthru

<?php
ob_implicit_flush(1);
echo '<PRE>';
echo 'BEGIN',PHP_EOL;
passthru('ping -c 5 8.8.8.8');
ob_flush();
flush();
echo 'DONE', PHP_EOL;
#Apache