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:
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
So, just for curiosity, I've created two scripts. One is write.php:
<?php
echo 'foo';
session_start();
$_SESSION['bar'] = 'baz';
?>
And the other one is read.php:
<?php
echo 'foo';
session_start();
var_dump($_SESSION['bar']);
?>
And surprisingly, the session is written and read even after echo
ing foo.
However, if I add a call to flush()
after the echo
s, Apache's error log reports:
[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
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…