Question

I am writing a php script and somewhere before my header() function i have printed text to the browser hereby causing my header() function give me a well known error:

Warning: Cannot modify header information - headers already sent.

Now my question is, I have the intentions of using ob_start() and ob_flush() before and after the header() function. But I once heard something like output buffer can affect the performance of one's application negatively. How true is that?

Or should I just stick with the idea of printing Javascript function to redirect the page.

Thanks for your time.

Was it helpful?

Solution

Using an output buffer requires the server to store the entire output of the PHP in RAM, so if it's a large page, you'll wind up using a fair amount of memory - and the server will also have to wait until the entire page is generated before sending it out, which could cause a small delay. But other than that, I don't think there's much of a disadvantage in using an output buffer. For what you want to do, it's certainly a reasonable solution.

OTHER TIPS

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

Test ob_start and friends to see if the performance difference matters. If it does, look for alternatives.

The easiest option is to move the header() call before your printing.

As you are likely performing a redirect with something like:

header('Location: /new/location/');

You should not print anything before this header() call because the client wouldn't do anything with the data you printed anyway (unless there's something I'm missing about HTTP).

(Javascript is not a good option for redirects, and nor is meta refreshing, unless you want to detect Javascript for some reason.)

Relocating in PHP-code after output can say about bad application design. But I don't know your situation and can propose two possible ways.

  1. Split code into model (data processing) and view (output) (see MVC). This means that you are making decision about relocating even before displaying anything. I'd called this way preferred.
  2. If you really need to show output (or other headers sent), common way is combining JS and HTML (in noscript):

    if (headers_sent()) {
        print('<script type="text/javascript">( document.location.replace ) ? document.location.replace("'.$location.'") : document.location.href = "'.$location.'";</script>'."\n".'<noscript><meta http-equiv="Refresh" content="0;URL='.$location.'" /></noscript>');
    } else {
        header('Location: '.$location);
        exit;
    }
    

P.S. This code is a piece of Fusebox framework.

just answering your last remark: you can redirect the page in php using header('Location: '.$url) it should go before any other output obviously and is advised to be followed by exit();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top