What is PHP Output Buffering?

PHPProgrammingServer Side Programming

Output Buffering is a method to tell the PHP engine to hold the output data before sending it to the browser. As we know PHP sent the output data to the browser in pieces, but if we utilize the output buffering mechanism, the output data is stored in a variable and sent to the browser as one piece at the end of the script.


Let's demonstrate with a simple example.

 Live Demo

   echo "Hello";
   $ob1 = ob_get_contents();
   echo "Tutorials Point";
   $ob2 = ob_get_contents();
   var_dump($ob1, $ob2);


string(5) "Hello"
string(20) "HelloTutorials Point"


In the above example ob_get_contents() grabs all of the data gathered since we called ob_start, i.e. everything in the buffer. After that send the output data at once.

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. Hence it decreases the execution time of PHP script.
  • If you've ever faced messages like "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you can solve it by Output Buffering.
Published on 26-Jun-2019 16:30:58