Chapter 11. Output Buffering

Without output buffering, PHP sends data to your web server as soon as it is ready. Not only is this slow because of the need to send lots of little bits of data, but it also means you are restricted in the order you can send data. Output buffering cures these ills by enabling you to store up your output and send it when you are ready to—or to not send it at all, if you so decide.

Why Use Output Buffering?

Output buffering lets you "send" cookies at any point in your script, ignoring the "headers first" HTTP rule. Internally, it causes PHP to store the cookies separate from the HTML data and then send them together at the end, in the correct order.

Once you are using output buffering, you can compress content before you send it. HTML is made up of lots of simple, repeating tags, and normal text on a site is easy to compress, which means that compressing your pages can drastically cut the amount of bandwidth your site (and your visitor!) uses, as well as how long it takes to transfer a page.

One final advantage is that output buffers are stackable, meaning that you can have several buffers working on top of each other, sending whichever ones you want to output.

Output buffering generally will not affect the speed of your web server by any great amount, unless you choose to compress your content. Compression takes up extra CPU time; however, the amount of page bandwidth you use will be cut by about 40%, which means your server will spend less time sending ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.