PHP cookies in a session handler
I have run into a very in开发者_如何学Cteresting problem trying to debug my custom PHP session handler. For some reason unknown to me I can set cookies all the way through the session handler right up until the very start of the write function.
As far as I know session handler calls go in this order.
open -> read -> write -> close
The open function sets a cookie just fine.
function open($save_path,$session_name)
{
require_once('database.php');
require_once('websiteinfo.php');
mysql_connect($sqllocation,$sql_session_user,$sql_session_pass);
@mysql_select_db($sql_default_db);
date_default_timezone_set('America/Los_Angeles');
setcookie("test","test");
return TRUE;
}
The read function can set a cookie right up until the very moment it returns a value.
function read($session_id)
{
$time = time();
$query = "SELECT * FROM 'sessions' WHERE 'expires' > '$time'";
$query_result = mysql_query($query);
$data = '';
/* fetch the array and start sifting through it */
while($session_array = mysql_fetch_array($query_result))
{
/* strip the slashes from the session array */
$session_array = $this->strip($session_array);
/* authenticate the user and if so return the session data */
if($this->auth_check($session_array,$session_id))
{
$data = $session_array['data'];
}
}
setcookie("testcookie1","value1",time()+1000,'/');
return $data;
}
The very first line of the write function is setting another cookie and it cannot because the headers are already sent.
From the manual for session_set_save_handler():
Note: The "write" handler is not executed until after the output stream is closed. Thus, output from debugging statements in the "write" handler will never be seen in the browser. If debugging output is necessary, it is suggested that the debug output be written to a file instead.
Essentially, writing changes to session data (calling the registered session write function) does not happen until PHP is almost completely done with its execution cycle. By this time, all your output has already been sent and it is not possible to modify the header information, so setcookie()
won't work.
You can have it write data earlier by using session_write_close().
精彩评论