Shall I use output buffering (ob_start) or not

962 views Asked by At

I have amended my PHP code in order to avoid using output buffering after finding out that it denotes a poor coding pattern. But still am using it where it is needed inevitably.

But, some articles say that using output buffering is beneficial as it combines the output into one , by default the output is broken into html and headers separately and is then displayed on the browser, but output buffering eliminates this breakage process, thus augmenting the speed of output display to the end user.

All this article stuff has left me in a dilemma to use or completely avoid output buffering. Am not sure if am completely right about its working and the points I have mentioned. So please guide me accordingly.

1

There are 1 answers

10
Jite On BEST ANSWER

There are times where the use of output buffering is a good thing to use, but to use it as lots of people do (the lazy way of not having to send headers before output for example) is not the right time.

The example you give, I do not know much about, but if its optimal, it might be one of the times where its good to use.
Its not forbidden to use ob_start(), its just the "wrong way" to use it the way I stated earlier.

The optimization you mention feels like a very low-level optimization, you might get a tad bit 'quicker' output, but there is usually a lot of other optimizations in a standard php-script that could speed it up before that is worth looking at!

edit: Example of a small script that don't use send headers before output vs one that do:

<?php
$doOutput = true;
$doRedirect = true;
$output = "";
if($doOutput == true){ 
    // $doOutput is true, so output is supposed to be printed.
    $output = "Some output yay!";
}
if($doRedirect == true){ 
    // but $doRedirect is also true, so redirect will be done.
    header("location:anotherpage.php");  // This will not produce an error cause there was no output!
    exit();
}
// The echo below will not be printed in the example, cause the $doRedirect var was true.
echo $output;

Instead of (this case will produce a header sent after output error):

<?php
$doOutput = true;
$doRedirect = true; 
if($doOutput == true){ 
    //Output will be printed, cause $doOutput is true.
    echo "Some output yay!";
}
if($doRedirect == true){ 
    // but $doRedirect is also true, so redirect will be done.
    header("location:anotherpage.php");  // This will produce an error cause output was already printed.
    exit();
}

edit2: Updated with a more obvious example!