session_start()在发送输出后工作 [英] session_start() works after output being sent
问题描述
我刚刚发现了一些奇怪的东西.我认为,正如PHP手册所述,在将任何输出发送到浏览器之前,必须先调用session_start()
:
I just noticed something strange. I thought that, as PHP's manual says, session_start()
must be called before any output is sent to the browser:
要使用基于cookie的会话,必须在输出任何内容到浏览器之前调用 session_start().
因此,出于好奇,我创建了两个脚本.一个是 write.php :
So, just for curiosity, I've created two scripts. One is write.php:
<?php
echo 'foo';
session_start();
$_SESSION['bar'] = 'baz';
?>
另一个是 read.php :
<?php
echo 'foo';
session_start();
var_dump($_SESSION['bar']);
?>
令人惊讶的是,甚至在echo
foo 之后,会话仍被写入和读取.
And surprisingly, the session is written and read even after echo
ing foo.
但是,如果我在echo
之后添加对flush()
的调用,Apache的错误日志将报告:
However, if I add a call to flush()
after the echo
s, Apache's error log reports:
[2012年1月3日星期二11:57:21] [错误] [客户端127.0.0.1] PHP警告:session_start():无法发送会话缓存限制器-标头已在/var/www/sessions/write.php中发送在第5行 [2012年1月3日星期二11:57:21] [错误] [客户端127.0.0.1] PHP堆栈跟踪: [2012年1月3日星期二11:57:21] [错误] [客户端127.0.0.1] PHP 1. {main}()/var/www/sessions/write.php:0 [2012年1月3日星期二11:57:21] [错误] [客户端127.0.0.1] PHP2.session_start()/var/www/sessions/write.php:5
[Tue Jan 03 11:57:21 2012] [error] [client 127.0.0.1] PHP Warning: session_start(): Cannot send session cache limiter - headers already sent in /var/www/sessions/write.php on line 5 [Tue Jan 03 11:57:21 2012] [error] [client 127.0.0.1] PHP Stack trace: [Tue Jan 03 11:57:21 2012] [error] [client 127.0.0.1] PHP 1. {main}() /var/www/sessions/write.php:0 [Tue Jan 03 11:57:21 2012] [error] [client 127.0.0.1] PHP 2. session_start() /var/www/sessions/write.php:5
所以,我的问题是:为什么在echo
处理完某些东西后正确编写了会话?它不是立即发送到浏览器吗?而且,如果是这样,是否意味着我可以在任何地方开始会话,只要我之前不致电flush()
?
So, my questions is: why is the session written correctly after echo
ing something? Isn't it immediately sent to the browser? And, if so, does it mean I can start the session anywhere, as long as I don't call flush()
before?
推荐答案
要使用基于cookie的会话,必须在调用session_start()之前 将任何内容输出到浏览器.
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
是的.服务器端cookie设置(与JavaScript cookie设置不同)通过发送HTTP标头来工作. HTTP标头位于实际文档之前:一旦开始发送文档,就没有地方放置其他标头了.
That's true. Server-side side cookie setting (unlike JavaScript cookie setting) works by sending an HTTP header. HTTP headers go before the actual document: once you start sending the document, there's no place for further headers.
在您的情况下,将发生以下情况:
In your case, what happens is that this line:
echo 'foo';
...实际上并不将输出发送到浏览器.而是将一些输出添加到队列中,稍后再发送.将PHP解释器配置为保留此输出,直到发生特定事件为止(可能脚本结束或队列达到特定大小).
... does not actually send output to the browser. Instead, it adds some output to a queue that will be sent later. The PHP interpreter is configured to hold this output until certain event happens (possibly, the scripts ends or the queue reaches certain size).
output_buffering 指令很可能是可疑的.
The output_buffering directive is the likely suspect.
这篇关于session_start()在发送输出后工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!