PHP: Streaming bash Command Output Line-by-Line in the Browser

To fire off a bash command from php code and output the results, you can use shell_exec(), but what if you need to see the whole output in real time as the script runs.

The other day I ran into the question of how to run a script or command on a linux server that generates lots of messages and watch all of them in real time in the browser.

First, let’s declare a function:

function disable_ob() {
  // Turn off output buffering
  ini_set('output_buffering', 'off');

  // Turn off output compression
  ini_set('zlib.output_compression', false);

  // Clear the output buffers
  ini_set('implicit_flush', true);
  ob_implicit_flush(true);

  while (ob_get_level() > 0) {
    // Get the current output level
    $level = ob_get_level();
    // End buffering
    ob_end_clean();
    // Break if the level didn't change (no new line appeared)
    if (ob_get_level() == $level) break;
  }

  // Disable buffering and compression for Apache
  if (function_exists('apache_setenv')) {
    apache_setenv('no-gzip', '1');
    apache_setenv('dont-vary', '1');
  }
}

It flushes the output buffer after every new line.

Next in the code we call this function and declare the command we’ll run (I took ping as an example):

disable_ob();
$command = 'ping 8.8.8.8';

For the result to look decent, wrap the following construct in <pre> ... </pre> tags

<?php
  system($command);
?>

When you open the page you’ll see the ping results to DNS server 8.8.8.8 in real time.

Categories:

Updated: