0

I don't understand this function. I read the PHP manual and don't get it. I am following a login tutorial and they used this function at the beginning of the script before session_start(). What is an internal buffer?

Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
unknownDude
  • 33
  • 1
  • 6
  • 1
    The manual explains the functionality of ob output buffering. It does not go into when and why you would you it. The question is very legitimate. – Misunderstood Jan 17 '15 at 22:10

1 Answers1

3

It stores all output in a buffer until it is flushed (e.g. ob_flush()).

It has many uses.

Example 1: If you are generating the HTML for a page that requires data look up, you can flush the HTML you have generated then do your look ups. This way the HTTP transport of your page begins while you do your data retrieval. You then continue outputting the rest of the page. Generally a good place to do a flush is right after the <body> tag. The Browser gets the First Byte sooner and if all the CSS is contained in the <head> the Browser can build the CSSOM. Ideally it takes less time to do the data retrieval than the transport of the HTML to the Browser. This way the data retrieval times has no impact on page load speed.
Example 2:
If you want to edit an image. You output the image and the buffer becomes the image raw data.

$image = ob_get_contents(); 

Make the edits. Empty (ob_clean()) the output buffer, then output the edited image with more HTML.
Example 3:
ob_start can be called with a callback function.

When the buffer is flushed the callback function is called by ob_start and the contents of the output buffer can be process by the function.

ob_start("ob_gzhandler");

ob_gzhandler will gzip the output. This is especially handy when your Server is not configured to compress output. Some servers are configured to compress on file extension rather than Content type. Or if the server is not configured to compress a particular MIME Content type.

If you server does not compress JSON (application/json) you can use ob_start("ob_gzhandler");

ob_start("ob_gzhandler");
header('Content-Type:application/json; charset=utf-8');

ob_start('ob_tidyhandler'); ob_start('ob_tidyhandler'); will tidy up your output. It will add missing Doctype, <head> closing tags that are missing, etc.

Misunderstood
  • 5,534
  • 1
  • 18
  • 25