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:
<?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(); ?> |
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.
0 comments:
Post a Comment