Typically PHP page sends the information back to the user once it completes its processing and the final output generated by it.

But there are certain scenarios where we require to display the intermediate processing to the user or we can say there are the cases when PHP outputs are required to display on users browser so that the user can analyze about what’s going on the server / what are the steps completed by server till now.

Advantages of output buffering for Web developers

  • Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it’s not being sent to the browser in pieces as PHP processes the HTML.
  • All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
  • If you’ve ever encountered the message “Warning: Cannot modify header information – headers already sent by (output)” while setting cookies, you’ll be happy to know that output buffering is your answer.

Let’s take a simple example – You are doing a file transfer from server to server, Here you have 1000 files in one folder and you are transferring these files to another server. So, in this case, you have two options-

1- Show output of the result when all files are transfered

2- Show output to user after each file transferred or say 25 files transferred

Now PHP Output Buffering comes into the picture to handle the second option, which is generally used everywhere for better User Experience.

Now let’s take second example ( a basic one ) for better and quick understanding. Suppose you want to make a for loop in PHP and each iteration has some Sleep in between which you can say your tasks. Now you want to see the output of each iteration rather than the output at the final stage.

You can find the code below.

<?php

ignore_user_abort(true);

echo '<style> th, td { border: 1px solid black; padding: 10px; } </style> ';

echo '<table>';
    echo '<tr>';
        echo '<th> Counter </th>';
        echo '<th> At Date </th>';
    echo '</tr>';

for ($i=0; $i < 400; $i++) { 
    ob_start();
    echo '<tr>';
        echo '<td>';
            echo $i;
        echo '</td>';

        echo '<td>';
            echo date('h:i:s');
        echo '</td>';
    echo '</tr>';
    sleep(1);
    ob_end_flush();
    ob_flush();
    flush();
}

echo '</table>';

?>

And Your Output will look like below

And every second you will see the table row appending to it.

Here Following main functions are used

ob_start — Turn on output buffering

ob_end_flush — Flush (send) the output buffer and turn off output buffering

ob_flush — Flush (send) the output buffer

flush — Flush system output buffer