👋 Enjoying the content? Subscribe to our Medium publication for more articles like this. 👇
Keep Learning

PHP Output Buffering

BY Atakan Demircioğlu
Table of Contents
Here are my notes about output buffering in PHP.

PHP Output Buffering

Here are my notes about output buffering in PHP.

What is PHP Output Buffering?

Basically, this is a method to tell the PHP engine to hold the output data before sending it to the browser.

  • Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script.
  • With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.
PHP Output Buffering image 1
PHP Output Buffering image 2

Advantages of output buffering

  • Turning on output buffering alone decreases the amount of time it takes to download and render our HTML in the browser. But it decreases the execution time of the PHP script.
  • You can solve “Warning: Cannot modify header information — headers already sent by (output)” errors with buffering
  • You can manipulate HTML or string before sending it to the browser
  • Probably the most popular reason for people using output buffering is that it allows you to compress the HTML you send to your visitors. Using compression makes your site load faster for your users, and also allows you to make more use of the bandwidth allocated to your server.
  • bool output_add_rewrite_var ( string name, string value) bool output_reset_rewrite_vars ( void ) is used generally for URL rewrite

Performance Considerations

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 a bit of CPU time, which will slow your server down.

Functions

ob_start() turns on output buffering. In other words, it creates the buffer (invisible holding cell) that will store all output after it is called.

ob_get_contents() grabs all of the data gathered since we called ob_start, i.e. everything in the buffer. Usually, you’ll assign this to a variable.

ob_clean() removes everything from the output buffer. Note that it does not output anything.

ob_flush() outputs content from the buffer. Note that it does not erase the buffer.

ob_end_clean() basically runs, discards the result, and turns off output buffering.

ob_end_flush() outputs content from the buffer and ends output buffering. It does not erase the buffer.

Full list here.

References

php