Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

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

I don't think it's reasonable.

Why is it actually such a rule?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...