dongqian2021 2010-04-22 23:09
浏览 32
已采纳

会话处理程序中的PHP cookie

I have run into a very interesting 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.

  • 写回答

1条回答 默认 最新

  • duanba4942 2010-04-22 23:17
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路