Question

I just saw a link on here with pretty much the same issue I had, but I want to make sure I understand. Here's the link: what is the role of ob_start() in here

So, his code had no real "output" -- no echos, no html, pretty much nothing. But he had an ob_start in it. Mine, like his, is legacy code and mine has NO output in it. All it does is update some tables. All of the answers I saw in this link addressed the actual function of the ob_start - I think only one addressed his real question, which was "what is the role of ob_start in THIS code?". So, if the code is a 'behind the scenes' script that is NOT outputting html or echoes or anything else, isn't the output buffer stuff useless? Thanks

Was it helpful?

Solution

No, it's not entirely useless, because the code there can still produce output through errors.

One of the answers already addressed this:

It means if they get halfway through outputting the page and decide there's an error, they can clear the buffer and output an error page instead. It also means you never get "couldn't sent headers, output already started" errors when trying to send HTTP headers.

In that specific code, there shouldn't be any output, but that doesn't mean that there can't be or that it would be easy to screw up and add output. Errors, warnings, and notices from any function call can add output if display_errors is on. There are many various ways of producing output in PHP and so an ob_start stops them all from actually sending that output to the response.

As said above, you might want to do this in order to:

  • Suppress the output altogether
  • Prevent errors in later calls to set HTTP headers (which require that no output already be sent).

OTHER TIPS

I believe it would allow you to suppress all output, for example, from error messages, and dump them into an error file. This is especially useful if you are going to be sending headers in your response at some point, and don't want error output to message with it.

For example:

<?php

ob_start();

//Do something that would generate a warning or notice.
//Output some headers
header("Content-type: application/json"); //This would fail if output had already been sent to the browser.

$contents = ob_get_contents();

//write contents to an error file or something.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top