PHP | ob_end_flush(), ob_end_clean() Functions

In the previous article on ob_start(), we learned how to start the output buffer; now we need to end the output buffering and send the whole HTML to the browser to render. We can do this by the help of functions ob_end_flush() and ob_end_clean().

ob_end_flush() Function

Syntax:



bool ob_end_flush ()

Parameters: The function doesn’t take any parameter.

Return Type: This function sends the HTML stored to browser and turns off output buffering. On success, TRUE is returned otherwise FALSE.

ob_end_clean() Function

Syntax:

bool ob_end_clean()

Parameters: The function doesn’t take any parameter.

Return Type: This function cleans the HTML stored and turns off output buffering. On success, TRUE is returned otherwise FALSE.

Below program illustrates the working of ob_end_flush() and ob_end_clean() in PHP:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// PHP code to illustrate the working of 
// ob_end_flush() and ob_end_clean()
  
// ob_end_flush()
ob_start();
echo "Hello Geek!"; //This will get printed.
ob_end_flush();
  
// ob_end_clean() 
ob_start();
echo "Hi Geek!"//This will not get printed.
ob_end_clean();
  
?>

chevron_right


Output:

Hello Geek!

Important points to note:

  • ob_end_flush() or ob_end_clean() are not necessary functions i.e. if a developer ever uses ob_start() without using the mentioned functions the webpage will appear to be working correctly displaying every content, but what happens in the back is nowhere near optimized. When PHP encounters ob_start() it allocates a new output buffer and concatenates every HTML that appears after it, if there is no terminating function then upon reaching the end the stored data is sent to the browser as a default action. Developers can create optimized web pages by terminating the output buffering when not required thus keeping the global stack clear.
  • There raises a question, if we use ob_end_clean() to clean the whole output buffer then why even use output buffering. We use ob_end_clean() with ob_get_contents() which first gets the contents as a string and then the output buffer is cleaned and turned off, this clears the global stack and keeps the whole content in a variable to be processed further.

Reference:



My Personal Notes arrow_drop_up

FullStack Developer of six websites Verified Freelancer with 19 complete projects and 4.9 rating Modest Lifelong Learner

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.