What is output buffering and why is one using it in PHP?
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.
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 );
}
?>
I know that this is an old question but I wanted to write my answer for visual learners. I couldn't find any diagrams explaining output buffering on the worldwide-web so I made a diagram myself in Windows mspaint.exe.
If output buffering is turned off, then echo will send data immediately to the Browser.
If output buffering is turned on, then an echo will send data to the output buffer before sending it to the Browser.
phpinfo
To see whether Output buffering is turned on / off please refer to phpinfo at the core section. The output_buffering directive will tell you if Output buffering is on/off.
In this case the output_buffering value is 4096 which means that the buffer size is 4 KB. It also means that Output buffering is turned on, on the Web server.
php.ini
It's possible to turn on/off and change buffer size by changing the value of the output_buffering directive. Just find it in php.ini, change it to the setting of your choice, and restart the Web server. You can find a sample of my php.ini below.
; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
; functions.
; Possible Values:
; On = Enabled and buffer is unlimited. (Use with caution)
; Off = Disabled
; Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096
The directive output_buffering is not the only configurable directive regarding Output buffering. You can find other configurable Output buffering directives here: http://php.net/manual/en/outcontrol.configuration.php
Example: ob_get_clean()
Below you can see how to capture an echo and manipulate it before sending it to the browser.
// Turn on output buffering
ob_start();
echo 'Hello World'; // save to output buffer
$output = ob_get_clean(); // Get content from the output buffer, and discard the output buffer ...
$output = strtoupper($output); // manipulate the output
echo $output; // send to output stream / Browser
// OUTPUT:
HELLO WORLD
Examples: Hackingwithphp.com
More info about Output buffer with examples can be found here:
http://www.hackingwithphp.com/13/0/0/output-buffering
The Output Control functions allow you
to control when output is sent from
the script. This can be useful in
several different situations,
especially if you need to send headers
to the browser after your script has
began outputting data. The Output
Control functions do not affect
headers sent using header() or
setcookie(), only functions such as
echo() and data between blocks of PHP
code.
http://php.net/manual/en/book.outcontrol.php
More Resources:
Output Buffering With PHP
As name suggest here memory buffer used to manage how the output of script appears.
Here is one very good tutorial for the topic
ob_start(); // turns on output buffering
$foo->bar(); // all output goes only to buffer
ob_clean(); // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents(); // buffer content is now an empty string
ob_end_clean(); // turn off output buffering
Buffers can be nested, so while one buffer is active, another ob_start() activates a new buffer. So ob_end_flush() and ob_flush() are not really sending the buffer to the output, but to the parent buffer. And only when there is no parent buffer, contents is sent to browser or terminal.
Nicely explained here: https://phpfashion.com/everything-about-output-buffering-in-php
UPDATE 2019. If you have dedicated server and SSD or better NVM, 3.5GHZ. You shouldn't use buffering to make faster loaded website in 100ms-150ms.
Becouse network is slowly than proccesing script in the 2019 with performance servers (severs,memory,disk) and with turn on APC PHP :) To generated script sometimes need only 70ms another time is only network takes time, from 10ms up to 150ms from located user-server.
so if you want be fast 150ms, buffering make slowl, becouse need extra collection buffer data it make extra cost. 10 years ago when server make 1s script, it was usefull.
Please becareful output_buffering have limit if you would like using jpg to loading it can flush automate and crash sending.
Cheers.
You can make fast river
or
You can make safely tama :)
This is a summary of output buffering in php. (XAMPP php.ini )
Output buffering is a mechanism for controlling how much output data
(excluding headers and cookies) PHP should keep internally before pushing that
data to the client. If your application's output exceeds this setting, PHP will send that data in chunks of roughly the size you specify. Turning on this setting and managing its maximum buffer size can yield some interesting side-effects depending on your application and web server. You may be able to send headers and cookies after you've already sent output through print or echo. You also may see performance benefits if your server is emitting less packets due to buffered output versus PHP streaming the output
as it gets it. On production servers, 4096 bytes is a good setting for performance
reasons.
Note: Output buffering can also be controlled via Output Buffering Control
functions.
Possible Values:
On = Enabled and buffer is unlimited. (Use with caution)
Off = Disabled
Integer = Enables the buffer and sets its maximum size in bytes.
Note: This directive is hardcoded to Off for the CLI SAPI
Default Value: Off
Development Value: 4096
Production Value: 4096
http://php.net/output-buffering
output_buffering=4096
Related
What is output buffering and why is one using it in PHP?
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.
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 );
}
?>
I know that this is an old question but I wanted to write my answer for visual learners. I couldn't find any diagrams explaining output buffering on the worldwide-web so I made a diagram myself in Windows mspaint.exe.
If output buffering is turned off, then echo will send data immediately to the Browser.
If output buffering is turned on, then an echo will send data to the output buffer before sending it to the Browser.
phpinfo
To see whether Output buffering is turned on / off please refer to phpinfo at the core section. The output_buffering directive will tell you if Output buffering is on/off.
In this case the output_buffering value is 4096 which means that the buffer size is 4 KB. It also means that Output buffering is turned on, on the Web server.
php.ini
It's possible to turn on/off and change buffer size by changing the value of the output_buffering directive. Just find it in php.ini, change it to the setting of your choice, and restart the Web server. You can find a sample of my php.ini below.
; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
; functions.
; Possible Values:
; On = Enabled and buffer is unlimited. (Use with caution)
; Off = Disabled
; Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096
The directive output_buffering is not the only configurable directive regarding Output buffering. You can find other configurable Output buffering directives here: http://php.net/manual/en/outcontrol.configuration.php
Example: ob_get_clean()
Below you can see how to capture an echo and manipulate it before sending it to the browser.
// Turn on output buffering
ob_start();
echo 'Hello World'; // save to output buffer
$output = ob_get_clean(); // Get content from the output buffer, and discard the output buffer ...
$output = strtoupper($output); // manipulate the output
echo $output; // send to output stream / Browser
// OUTPUT:
HELLO WORLD
Examples: Hackingwithphp.com
More info about Output buffer with examples can be found here:
http://www.hackingwithphp.com/13/0/0/output-buffering
The Output Control functions allow you
to control when output is sent from
the script. This can be useful in
several different situations,
especially if you need to send headers
to the browser after your script has
began outputting data. The Output
Control functions do not affect
headers sent using header() or
setcookie(), only functions such as
echo() and data between blocks of PHP
code.
http://php.net/manual/en/book.outcontrol.php
More Resources:
Output Buffering With PHP
As name suggest here memory buffer used to manage how the output of script appears.
Here is one very good tutorial for the topic
ob_start(); // turns on output buffering
$foo->bar(); // all output goes only to buffer
ob_clean(); // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents(); // buffer content is now an empty string
ob_end_clean(); // turn off output buffering
Buffers can be nested, so while one buffer is active, another ob_start() activates a new buffer. So ob_end_flush() and ob_flush() are not really sending the buffer to the output, but to the parent buffer. And only when there is no parent buffer, contents is sent to browser or terminal.
Nicely explained here: https://phpfashion.com/everything-about-output-buffering-in-php
UPDATE 2019. If you have dedicated server and SSD or better NVM, 3.5GHZ. You shouldn't use buffering to make faster loaded website in 100ms-150ms.
Becouse network is slowly than proccesing script in the 2019 with performance servers (severs,memory,disk) and with turn on APC PHP :) To generated script sometimes need only 70ms another time is only network takes time, from 10ms up to 150ms from located user-server.
so if you want be fast 150ms, buffering make slowl, becouse need extra collection buffer data it make extra cost. 10 years ago when server make 1s script, it was usefull.
Please becareful output_buffering have limit if you would like using jpg to loading it can flush automate and crash sending.
Cheers.
You can make fast river
or
You can make safely tama :)
This is a summary of output buffering in php. (XAMPP php.ini )
Output buffering is a mechanism for controlling how much output data
(excluding headers and cookies) PHP should keep internally before pushing that
data to the client. If your application's output exceeds this setting, PHP will send that data in chunks of roughly the size you specify. Turning on this setting and managing its maximum buffer size can yield some interesting side-effects depending on your application and web server. You may be able to send headers and cookies after you've already sent output through print or echo. You also may see performance benefits if your server is emitting less packets due to buffered output versus PHP streaming the output
as it gets it. On production servers, 4096 bytes is a good setting for performance
reasons.
Note: Output buffering can also be controlled via Output Buffering Control
functions.
Possible Values:
On = Enabled and buffer is unlimited. (Use with caution)
Off = Disabled
Integer = Enables the buffer and sets its maximum size in bytes.
Note: This directive is hardcoded to Off for the CLI SAPI
Default Value: Off
Development Value: 4096
Production Value: 4096
http://php.net/output-buffering
output_buffering=4096
Is it possible to know how many bytes sent to the client browser using php? My pages are created dynamically, so the size isn't fixed.
Using php's output buffering
// start output buffering
ob_start();
// create your page
// once the page is ready, measure the size of the output buffer
$length = ob_get_length();
// and emit the page, stop buffering and flush the buffer
ob_get_flush();
As usual with php, these functions are pretty well documented in the standard documentation, don't forget to read the user contributed notes.
You can see this in your webserver's access log file.
But you can also code some php to get an answer like this:
ob_start();
echo "your content"
$data = ob_get_contents();
$size = strlen($data);
see also: Measure string size in Bytes in php
What is output buffering and why is one using it in PHP?
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.
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 );
}
?>
I know that this is an old question but I wanted to write my answer for visual learners. I couldn't find any diagrams explaining output buffering on the worldwide-web so I made a diagram myself in Windows mspaint.exe.
If output buffering is turned off, then echo will send data immediately to the Browser.
If output buffering is turned on, then an echo will send data to the output buffer before sending it to the Browser.
phpinfo
To see whether Output buffering is turned on / off please refer to phpinfo at the core section. The output_buffering directive will tell you if Output buffering is on/off.
In this case the output_buffering value is 4096 which means that the buffer size is 4 KB. It also means that Output buffering is turned on, on the Web server.
php.ini
It's possible to turn on/off and change buffer size by changing the value of the output_buffering directive. Just find it in php.ini, change it to the setting of your choice, and restart the Web server. You can find a sample of my php.ini below.
; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
; functions.
; Possible Values:
; On = Enabled and buffer is unlimited. (Use with caution)
; Off = Disabled
; Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096
The directive output_buffering is not the only configurable directive regarding Output buffering. You can find other configurable Output buffering directives here: http://php.net/manual/en/outcontrol.configuration.php
Example: ob_get_clean()
Below you can see how to capture an echo and manipulate it before sending it to the browser.
// Turn on output buffering
ob_start();
echo 'Hello World'; // save to output buffer
$output = ob_get_clean(); // Get content from the output buffer, and discard the output buffer ...
$output = strtoupper($output); // manipulate the output
echo $output; // send to output stream / Browser
// OUTPUT:
HELLO WORLD
Examples: Hackingwithphp.com
More info about Output buffer with examples can be found here:
http://www.hackingwithphp.com/13/0/0/output-buffering
The Output Control functions allow you
to control when output is sent from
the script. This can be useful in
several different situations,
especially if you need to send headers
to the browser after your script has
began outputting data. The Output
Control functions do not affect
headers sent using header() or
setcookie(), only functions such as
echo() and data between blocks of PHP
code.
http://php.net/manual/en/book.outcontrol.php
More Resources:
Output Buffering With PHP
As name suggest here memory buffer used to manage how the output of script appears.
Here is one very good tutorial for the topic
ob_start(); // turns on output buffering
$foo->bar(); // all output goes only to buffer
ob_clean(); // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents(); // buffer content is now an empty string
ob_end_clean(); // turn off output buffering
Buffers can be nested, so while one buffer is active, another ob_start() activates a new buffer. So ob_end_flush() and ob_flush() are not really sending the buffer to the output, but to the parent buffer. And only when there is no parent buffer, contents is sent to browser or terminal.
Nicely explained here: https://phpfashion.com/everything-about-output-buffering-in-php
UPDATE 2019. If you have dedicated server and SSD or better NVM, 3.5GHZ. You shouldn't use buffering to make faster loaded website in 100ms-150ms.
Becouse network is slowly than proccesing script in the 2019 with performance servers (severs,memory,disk) and with turn on APC PHP :) To generated script sometimes need only 70ms another time is only network takes time, from 10ms up to 150ms from located user-server.
so if you want be fast 150ms, buffering make slowl, becouse need extra collection buffer data it make extra cost. 10 years ago when server make 1s script, it was usefull.
Please becareful output_buffering have limit if you would like using jpg to loading it can flush automate and crash sending.
Cheers.
You can make fast river
or
You can make safely tama :)
This is a summary of output buffering in php. (XAMPP php.ini )
Output buffering is a mechanism for controlling how much output data
(excluding headers and cookies) PHP should keep internally before pushing that
data to the client. If your application's output exceeds this setting, PHP will send that data in chunks of roughly the size you specify. Turning on this setting and managing its maximum buffer size can yield some interesting side-effects depending on your application and web server. You may be able to send headers and cookies after you've already sent output through print or echo. You also may see performance benefits if your server is emitting less packets due to buffered output versus PHP streaming the output
as it gets it. On production servers, 4096 bytes is a good setting for performance
reasons.
Note: Output buffering can also be controlled via Output Buffering Control
functions.
Possible Values:
On = Enabled and buffer is unlimited. (Use with caution)
Off = Disabled
Integer = Enables the buffer and sets its maximum size in bytes.
Note: This directive is hardcoded to Off for the CLI SAPI
Default Value: Off
Development Value: 4096
Production Value: 4096
http://php.net/output-buffering
output_buffering=4096
I have a PHP script which takes a while to process and I wanted to get the site to display it's progress while it is running.
I have been having problems displaying the contents of the output buffer while a PHP code is running. I have been trying the use of ob_implicit_flush(true), ob_end_flush() and ob_flush() with no success.
After looking for a fair bit at the PHP manual on php.net I have come across a comment by Lee saying
As of August 2012, all browsers seem to show an all-or-nothing
approach to buffering. In other words, while php is operating, no
content can be shown.
In particular this means that the following workarounds listed further
down here are ineffective:
1) ob_flush (), flush () in any combination with other output
buffering functions;
2) changes to php.ini involving setting output_buffer and/or
zlib.output_compression to 0 or Off;
3) setting Apache variables such as "no-gzip" either through
apache_setenv () or through entries in .htaccess.
So, until browsers begin to show buffered content again, the tips
listed here are moot.
see here
If he is correct, is there an alternative I can use to display the progress of the script running?
[edit]
Looks like Lee could be right. I have been doing some testing and here is an example of the problem
<?php
ob_implicit_flush(true);
ob_end_flush();
for ($i=0; $i<5; $i++) {
echo $i.'<br>';
sleep(1);
}
?>
Should display 0 to 4 with a second in between. What actually happens is that the site waits 5 seconds then displays 0 to 4 immediately. It is waiting for the script to complete then displays everything in one go.
I have had output_buffering = Off in my php.ini file and tried setting it to 1 and 4096 (4096 being 4KB) and it still does the same.
Check the buffer size and make an "empty" dummy of that size, for example...
$flushdummy="";
for ($i=0; $i<700; $i++) { $flushdummy=$flushdummy." "; }
$flushdummy=$flushdummy."\n";
then, when output is desired, add the dummy to the output, plus the flush:
echo "here I am<br />", $flushdummy;
flush();
#ob_flush();
I can't for the life of me get the PHP flush function to work properly, using WAMP. Here is some sample code, commented out are all of the different things I've tried:
//apache_setenv('no-gzip', 1); // returns error that apache_setenv does not exist
//ini_set('zlib.output_compression',0);
//ini_set('implicit_flush',1);
//ob_end_clean();
//for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
//ob_implicit_flush(1);
set_time_limit(0);
echo "<pre>";
for ($i = 0; $i < 100; ++$i) {
echo $i.' '.time().str_repeat(' ',256)."\n";
//ob_flush(); // returns error without output buffering enabled
flush();
usleep(100000);
}
It seems no matter what I do, I always get the results all together in one giant chunk.
Edit:
I've uploaded the same exact code to a server running on cPanel/linux, and it works perfect in all browsers. Why can't I get it to work properly on a localhost WAMP server??
flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.
Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.
Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.
Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the tag of the outermost table is seen.
Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.
php.net
Try using ob_flush() before flush();