You might have heard about output buffering while you code in PHP. I will tell you what it is and how to use it simply.
“Output Buffering” Meaning
“Buffering” in computing means
store (data) in a buffer while it is being processed or transferred.
This is exactly what PHP does too. But, the default mechanism is not this. It is turned off by default i.e :
data is not stored in a buffer while it is being processed or transferred.
Output Buffering Off (Default)
When a user requests a PHP page from your server, PHP processes the page and on the fly, the HTML is sent to the browser (user).
This means, that HTML is received by the browser in chunks during the connection and the connection won’t close until the processing is finished.
This is the default setting in PHP i.e output buffer turned off.
Output Buffering On
As the word meaning says, the processed HTML is stored in a variable until the processing is finished and when it is finished, the contents of the variable is sent.
So, instead of chunks of data, the full data is sent at an instant. These are the advantages if output buffering is turned on :
Able to do redirects even at the end of page :
Hello World <?php header(“Location: https://subinsb.com”); ?>
Normally, the above code will print “headers already sent error”. But, with output buffering turned on, this error won’t be produced.
- “Warning: Cannot modify header information – headers already sent by (output)” error and all such errors won’t be produced
Toggle Output Buffering
You can choose to turn on/off output buffering permanently by editing “php.ini” file. Find “output_buffering” key and set the value :
<a class="link" href="http://php.net/manual/en/outcontrol.configuration.php#ini.output-buffering">output_buffering</a>=On
You can also set it by “.htaccess” file :
php_flag output_buffering On