PHP ob_flush() Function

What is PHP ob_flush() Function?

If you want to flush (send) the content of the buffer that you created with functions like ob_start(), use ob_flush() function.

When you declare an ob_start() function, a new layer/level of buffer is added. In this stage, if you run ob_flush() function, PHP sends data from this layer to the next lower buffer layer/level.

Syntax:

ob_flush()

Parameters:

The function has no parameter.

Return Values:

The function returns-

  • TRUE – on success
  • FALSE – on failure

ob_flush() Examples:

<?php
ob_start();
echo str_pad("Wait 1 Second... ",4096);
ob_flush();
flush();
sleep(1);
echo"The End.";
?>

Output:

Wait 1 Second… The End.

Explanation:

By default, when the script starts, it is in first buffer level. By line 2, another buffer level adds. The string “Wait 1 second… ” goes to this level‘s buffer. The ob_flush() function in the next line sends this string to the lower level’s buffer.  Then, flush() sends this output to the browser. The sleep(1) function delays the script execution for 1 second and finally as the script ends with the last echo statement, the statement displays in the browser.

Note: From the above explanation, you see that as ob_flush() sends output to the lower level’s buffer that was initiated by PHP script, the ob_flush() alone can’t sends the output to the browser. So, to display your text immediately to the browser use ob_flush() and then flush() in this order. flush() flushes content from Apache’s buffer.

PHP Version Support:

PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8

Summary: PHP ob_flush() Function

ob_flush() function is a built-in PHP function and part of the PHP’s Output Control functions. It flushes out the content of the topmost active buffer.

Reference:

https://www.php.net/manual/en/function.ob-flush.php