What is output buffering in PHP?
Asked Answered
R

7

231

What is output buffering and why would you use it in PHP?

Ruralize answered 14/5, 2010 at 5:29 Comment(0)
D
301

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.
Dorsum answered 14/5, 2010 at 6:12 Comment(8)
+1. Here's another helpful link: php.net/manual/en/function.ob-start.php - also helpful when dealing with a function that echos a value that you'd rather store in a variable.Caliper
Is really everything buffered up to the end, or will the page just come in chunks if I have a reeeeally long page?Laconism
@Laconism if you start output buffering with ob_start(), really everything is buffered. there is an optional second parameter to ob_start(), int $chunk_size, which, if set, will cause the buffer to be flushed after any output call which causes the buffer's length to equal or exceed this size.Dorsum
In what specific way can output buffering be the answer to the "Cannot modify header information" error? Surely you can't just turn it on and leave it like that for everything else right?Show
If you get "Warning: Cannot modify header information" , that means you need to audit your code first as enabling output buffering is a fix of the symptom and not the cause. Something is writing before it's turn. So I disagree, but not enough to bump the answer down.Certainly
I am using ob_start() to workaround a "set cookie" issue and outputting an XML document in the last line of my code. The XML outputs to the page as expected but I was wondering if it is a best practice to call ob_end_flush() at the end of the script.Thames
I see only adventages of using buffering, so why It is not enabled by default in php?Malm
I am using yii2 the ob_start(); solved my problem, I was getting this error. 'An Error occurred while handling another error: exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /var/www/html/frontend/controllers/Student_invoiceController.php on line 234.' in /var/www/html/vendor/yiisoft/yii2/web/Response.php:366'Sf
A
72

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 );
    }
?>
Araroba answered 14/5, 2010 at 6:18 Comment(2)
Same question here as for Ax: isn't starting output buffering without turning it back off later, going to make your script run into all kinds of problems?Show
Buffer is flushed when you call one of the flush methods (e.g. ob_flush() or ob_end_flush()). Contents of the buffer are also flushed when your script ends, abruptly or otherwise so there shouldn't be a problem.Araroba
A
37

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.

enter image description here

If output buffering is turned on, then an echo will send data to the output buffer before sending it to the Browser.

enter image description here

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.

enter image description here 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

Abecedarian answered 29/10, 2018 at 9:5 Comment(2)
Question, do I need to have display_errors set to On for this buffer to be captured?Swagerty
display_errors and output_buffering are two different things. Correct me if I'm wrong, setting display_errors to "1" is not necessary.Abecedarian
N
10

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

Nez answered 14/5, 2010 at 6:14 Comment(0)
G
5
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

Grown answered 23/8, 2018 at 7:20 Comment(0)
E
0

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 :)

Esch answered 7/1, 2019 at 14:29 Comment(0)
Z
-1

Output Buffering ob_start() function also accept callback function.

You can see the code below. There is a function callback that accepts an argument. Here $buffer is the string holding content from the ob_start() to ob_end_flush().

<?php

function callback($buffer)
{
  // it will replace football with cricket
  return (str_replace("football", "cricket", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It like football.</p>
</body>
</html>
<?php

ob_end_flush();

?>

The output of the above code is:

<html>
<body>
<p>I like cricket.</p>
</body>
</html>

I also need to explain that output buffering function also works in nested scopes. example:

<?php
    
    ob_start();   
    echo "Hello"; 
        
        ob_start();              // nested ob_start()
        echo "PHP";              
        $v1 = ob_get_contents(); // Stores "PHP" in $v1 variable.
        ob_end_flush();
        
    echo "World"; 
    $v2 = ob_get_contents(); // Stores "Hello PHP World" in $v2 variable.
    ob_end_flush();          

?>
Zimmer answered 13/7, 2023 at 7:6 Comment(1)
You can't just copy/paste code without given any referenceBaud

© 2022 - 2024 — McMap. All rights reserved.