Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is output buffering?

What is output buffering and why is one using it in PHP?

like image 650
Abhimanyu Avatar asked May 14 '10 05:05

Abhimanyu


People also ask

What is output buffers?

An output buffer is a location in memory or cache where data ready to be seen is held until the display device is ready. Buffer, Memory terms, Output.

What is output buffering Python?

Summary: Python output buffering is the process of storing the output of your code in buffer memory. Once the buffer is full, the output gets displayed on the standard output screen.

What is output buffer in C?

C uses a buffer to output or input variables. The buffer stores the variable that is supposed to be taken in (input) or sent out (output) of the program. A buffer needs to be cleared before the next input is taken in.


2 Answers

Output Buffering for Web Developers, a Beginner’s Guide:

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.

Advantages of output buffering for Web developers

  • Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
  • All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
  • If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.
like image 134
ax. Avatar answered Oct 15 '22 04:10

ax.


Output buffering is used by PHP to improve performance and to perform a few tricks.

  • You can have PHP store all output into a buffer and output all of it at once improving network performance.

  • You can access the buffer content without sending it back to browser in certain situations.

Consider this example:

<?php     ob_start( );     phpinfo( );     $output = ob_get_clean( ); ?> 

The above example captures the output into a variable instead of sending it to the browser. output_buffering is turned off by default.

  • You can use output buffering in situations when you want to modify headers after sending content.

Consider this example:

<?php     ob_start( );     echo "Hello World";     if ( $some_error )     {         header( "Location: error.php" );         exit( 0 );     } ?> 
like image 29
Salman A Avatar answered Oct 15 '22 04:10

Salman A