why ob_start() must come ahead of session_start() to work in PHP?

omg picture omg · Sep 20, 2009 · Viewed 33.4k times · Source

I don't think it's reasonable.

Why is it actually such a rule?

Answer

Pascal MARTIN picture Pascal MARTIN · Sep 20, 2009

In the "normal case", I don't think ob_start has to be called before session_start -- nor the other way arround.

Quoting the manual page of session_start, though :

session_start() will register internal output handler for URL rewriting when trans-sid is enabled. If a user uses ob_gzhandler or like with ob_start(), the order of output handler is important for proper output. For example, user must register ob_gzhandler before session start.

But this is some kind of a special case : the thing is, here, that the order of output handlers is important : if you want one handler to modify things the other did, they have to be executed in the "right" order.


Generally, if you don't use that kind of handlers (Apache and mod_deflate do a great job when it comes to compressing output, for instance), the only thing that matters is that headers must not be sent before you call session_start (because, depending on your configuration, session_start sends cookies, which are passed as HTTP headers).

And headers are sent as soon as any piece of data has to be sent -- ie, as soon as there is any output, even one whitespace outside of <?php ?> tags :

Note: If you are using cookie-based sessions, you must call session_start() before anything is outputted to the browser.

ob_start indicates that PHP has to buffer data :

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

This way, output is not sent before you actually say, yourself, "send the data". This means headers are not send immediatly -- which means session_start can be called later, even if there should have been output, if ob_start had not been used.


Hope this makes things a bit more clear...