Codeigniter随机会话注销(已经尝试重写会话类并提高session_time_to_update [英] Codeigniter random session logouts (Already tried override session class AND raising session_time_to_update

查看:1262
本文介绍了Codeigniter随机会话注销(已经尝试重写会话类并提高session_time_to_update的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已尝试过以下两种建议:
Codeigniter会话陷阱ajax调用



但是即使使用 $ config ['sess_time_to_update'] = PHP_INT_MAX 看到随机退出。



我也采纳了建立类 MY_Session



用户仍在报告随机退出,我的日志也似乎表明了这一点。



编辑:这是我的会话配置:

  $ config ['sess_cookie_name'] ='phppos'; 
$ config ['sess_expiration'] = 86400;
$ config ['sess_expire_on_close'] = TRUE;
$ config ['sess_encrypt_cookie'] = FALSE;
$ config ['sess_use_database'] = TRUE;
$ config ['sess_table_name'] ='sessions';
$ config ['sess_match_ip'] = FALSE;
$ config ['sess_match_useragent'] = TRUE;
$ config ['sess_time_to_update'] = PHP_INT_MAX;


解决方案

我认为你正在遭受AJAX会话竞争条件。我有同样的问题,我解决它覆盖的CI会话类。您在这里有文章:



http://www.hiretheworld.com/blog/tech-blog/codeigniter-session-race-conditions



最干净的事情是使用MY_Session类,在您的库文件夹中,然后覆盖上面链接中写的方法。抱歉缺少缩排,:P

  class MY_Session extends CI_Session 
{
public function __construct )
{
parent :: __ construct();
}


/ ******************************** *************************************
*覆盖codeigniter会话库
*
*在session_id更新期间处理竞争条件。
* - 保持旧的会话ID,以防我们处理race
*条件。
* - 更改标记为字符串old_session_id_changes。
*
*会话表更改:
* ALTER TABLE`sessions'ADD COLUMN`old_session_id` VARCHAR(40)DEFAULT NULL COMMENT'old session id'AFTER`user_data`,
* ADD INDEX`old_session_id`(`old_session_id`);
* DELETE FROM`sessions`;
********************************************** *********************** /

/ **
*提取当前会话数据(如果存在)
*
* @return bool
* /
public function sess_read()
{
//获取cookie
$ session = $ this- > CI-> input-> cookie($ this-> sess_cookie_name);

//没有cookie?再见残酷的世界... ...
if($ session === NULL)
{
log_message('debug','没有找到会话cookie。
return FALSE;
}

//解密cookie数据
if($ this-> sess_encrypt_cookie === TRUE)
{
$ session = $ this - > CI-> encrypt-> decode($ session);
}
else
{
//加密没有使用,所以我们需要检查md5散列
$ hash = substr($ session,strlen )-32); // get last 32 chars
$ session = substr($ session,0,strlen($ session)-32);

// md5是否匹配?这是为了防止用户空间中会话数据的操作
if($ hash!== md5($ session。$ this-> encryption_key))
{
log_message('error'会话cookie数据不符合预期,这可能是一个可能的黑客尝试。
$ this-> sess_destroy();
return FALSE;
}
}

//取消序列化会话数组
$ session = $ this-> _unserialize($ session);

//会话数据是否以正确的格式解序列化?
if(!is_array($ session)OR!isset($ session ['session_id'],$ session ['ip_address'],$ session ['user_agent'],$ session ['last_activity']))
{
$ this-> sess_destroy();
return FALSE;
}

//会话是否为当前会话?
if(($ session ['last_activity'] + $ this-> sess_expiration)< $ this-> now)
{
$ this-> sess_destroy
return FALSE;
}

// IP是否匹配?
if($ this-> sess_match_ip === TRUE& $ session ['ip_address']!$ $ this-> CI-> input-> ip_address())
{
$ this-> sess_destroy();
return FALSE;
}

//用户代理是否匹配?
if($ this-> sess_match_useragent === TRUE&& trim($ session ['user_agent'])!== trim(substr($ this-> CI-> input-> user_agent(),0,120)))
{
$ this-> sess_destroy();
return FALSE;
}

// DB中是否有相应的会话?
if($ this-> sess_use_database === TRUE)
{
/ *
* begin old_session_id_changes
*
*搜索session_id和old_session_id
*传入会话ID的字段。
*
*以前是:
* $ this-> CI-> db->其中('session_id',$ session ['session_id']);
*
*手动创建OR条件,因为它对现有代码造成最小的
*干扰。
*
*存储cookie中的会话ID,以便我们可以看到以后是否通过旧会话id进入了
*。
* /
$ this-> CI-> db-> where('(session_id ='。$ this-> CI-> db-& session_id'])。'OR old_session_id ='。$ this-> CI-> db-> escape($ session ['session_id'])。
$ this-> cookie_session_id = $ session ['session_id'];
/ *
* end old_session_id_changes
* /

if($ this-> sess_match_ip === TRUE)
{
$ this-> CI-> db->其中('ip_address',$ session ['ip_address']);
}

if($ this-> sess_match_useragent === TRUE)
{
$ this-> CI-> db->其中'user_agent',$ session ['user_agent']);
}

$ query = $ this-> CI-> db-> limit(1) - > get($ this-> sess_table_name);

//没有结果?杀了它!
if($ query-> num_rows()=== 0)
{
$ this-> sess_destroy();
return FALSE;
}

//有自定义数据吗?如果是这样,将它添加到主会话数组
$ row = $ query-> row();
if(!empty($ row-> user_data))
{
$ custom_data = $ this-> _unserialize($ row-> user_data);

if(is_array($ custom_data))
{
foreach($ custom_data as $ key => $ val)
{
$ session [ $ key] = $ val;
}
}
}

/ *
* begin old_session_id_changes
*
*将session_id从数据库中拉出curent
* session id因为旧的是陈旧的。
*
*从数据库中拉出old_session_id,以便我们可以将
*与当前(cookie)会话id进行比较。
* /
$ session ['session_id'] = $ row-> session_id;
$ session ['old_session_id'] = $ row-> old_session_id;
/ *
* end old_session_id_changes
* /
}

//会话有效!
$ this-> userdata = $ session;
unset($ session);

return TRUE;
}

// ----------------------------------- ---------------------------------

/ **
*写会话数据
*
* @return void
* /
public function sess_write()
{
//我们将自定义数据保存到DB ?如果没有,我们所做的就是更新cookie
if($ this-> sess_use_database === FALSE)
{
$ this-> _set_cookie
return;
}

//设置自定义userdata,我们将在第二个设置的会话数据
$ custom_userdata = $ this-> userdata;
$ cookie_userdata = array();

//继续之前,我们需要确定是否有任何自定义数据要处理。
//让我们通过删除默认的索引来确定这一点,看看数组中是否还有剩余的东西
//并设置session数据
foreach(array('session_id ','ip_address','user_agent','last_activity')as $ val)
{
unset($ custom_userdata [$ val]);
$ cookie_userdata [$ val] = $ this-> userdata [$ val];
}

/ *
* begin old_session_id_changes
*
* old_session_id有自己的字段,但它不需要转到
*一个cookie,因为我们总是从数据库中检索它。
* /
unset($ custom_userdata ['old_session_id']);
/ *
* end old_session_id_changes
* /

//我们找到任何自定义数据吗?如果没有,我们把空数组变成字符串
//,因为没有理由在DB中序列化和存储一个空数组
if(count($ custom_userdata)=== 0)
{
$ custom_userdata ='';
}
else
{
//序列化自定义数据数组,以便我们可以存储它
$ custom_userdata = $ this-> _serialize($ custom_userdata);
}

//运行更新查询
$ this-> CI-> db->其中('session_id',$ this-> userdata [' session_id']);
$ this-> CI-> db-> update($ this-> sess_table_name,array('last_activity'=> $ this-> userdata ['last_activity'],'user_data' > $ custom_userdata));

//写cookie。注意,我们手动将cookie数据数组传递给
// _set_cookie()函数。通常,该函数将存储$ this-> userdata,但
//在这种情况下,该数组包含自定义数据,我们不想在cookie中。
$ this-> _set_cookie($ cookie_userdata);
}

// ----------------------------------- ---------------------------------

/ **
*更新现有会话
*
* @return void
* /
public function sess_update()
{
//我们只每五分钟更新一次会话默认情况下
if(($ this-> userdata ['last_activity'] + $ this-> sess_time_to_update)> = $ this-> now)
{
return;
}

如果我们不使用数据库会话
//通过推送所有的userdata到cookie,_set_cookie()将为我们处理这个。
$ cookie_data = NULL;

/ *
* begin old_session_id_changes
*
*如果我们通过索引到
* old_session_id不需要重新生成会话) ,但是发送cookie反正确保
*客户端有一个新的cookie的副本。
*
*如果我们不使用数据库
*存储额外数据,请先进行isset检查。 old_session_id字段仅存在于
*数据库中。
* /
if((isset($ this-> userdata ['old_session_id']))&&
($ this-> cookie_session_id === $ this-> ; userdata ['old_session_id']))
{
//显式地设置cookie只有我们的会话数据
$ cookie_data = array();
foreach(array('session_id','ip_address','user_agent','last_activity')as $ val)
{
$ cookie_data [$ val] = $ this-> userdata [$ val];
}

$ this-> _set_cookie($ cookie_data);
return;
}
/ *
* end old_session_id_changes
* /

//保存旧会话ID,以便我们知道哪个记录为
/ / update在数据库中,如果我们需要它
$ old_sessid = $ this-> userdata ['session_id'];
$ new_sessid ='';
do
{
$ new_sessid。= mt_rand(0,mt_getrandmax());
}
while(strlen($ new_sessid)< 32);

//为了使会话ID更安全,我们将它与用户的IP组合。
$ new_sessid。= $ this-> CI-> input-> ip_address );

//将其转换为哈希并更新会话数据数组
$ this-> userdata ['session_id'] = $ new_sessid = md5(uniqid($ new_sessid,TRUE)) ;
$ this-> userdata ['last_activity'] = $ this-> now;

//如果需要,更新DB中的会话ID和last_activity字段
if($ this-> sess_use_database === TRUE)
{
//显式地设置cookie只有我们的会话数据
$ cookie_data = array();
foreach(array('session_id','ip_address','user_agent','last_activity')as $ val)
{
$ cookie_data [$ val] = $ this-> userdata [$ val];
}

/ *
* begin old_session_id_changes
*
*将旧会话标识保存到old_session_id字段中,以便
*稍后再参考。
*
*如果有零个受影响的行
*,则重写cookie的会话ID,因为这意味着另一个请求更改了当前请求下的数据库
*。在这种情况下,我们要返回一个与上一个请求一致的
*值。重新立即
*更新后调用此处以最小化时序问题。这个
*应该在支持它们的数据库的事务中。
*
*还重写了userdata,以便将来调用sess_write
*将输出正确的cookie数据。
*
*以前是:
* $ this-> CI-> db-> query($ this-> CI-> db-> update_string this-> sess_table_name,array('last_activity'=> $ this-> now,'session_id'=> $ new_sessid),array('session_id'=> $ old_sessid)
* /
$ this-> CI-> db-> query($ this-> CI-> db-> update_string($ this-> sess_table_name,array last_activity'=> $ this-> now,'session_id'=> $ new_sessid,'old_session_id'=> $ old_sessid),array('session_id'=> $ old_sessid)

if($ this-> CI-> db-> affected_rows()=== 0)
{
$ this-> CI-& - > where('old_session_id',$ this-> cookie_session_id);
$ query = $ this-> CI-> db-> get($ this-> sess_table_name);

//如果没有结果,我们失去了会话的跟踪,所以
//不设置cookie,只返回。
if($ query-> num_rows()== 0)
{
return;
}

$ row = $ query-> row();
foreach(array('session_id','ip_address','user_agent','last_activity')as $ val)
{
$ this-> userdata [$ val] = $ row - > $ val;
$ cookie_data [$ val] = $ this-> userdata [$ val];
}

//将请求会话ID设置为旧会话ID,以便我们
//不会再尝试在此请求上重新生成cookie -
//只是为了再次调用sess_update(它不是
//)。
$ this-> cookie_session_id = $ this-> userdata ['old_session_id'];
}
/ *
* end old_session_id_changes
* /
}

//写cookie
$ this-> ; _set_cookie($ cookie_data);
}

/ ************************************ *********************************
* end覆盖到codeigniter会话库
** **************************************************** $ *** $

I have tried both suggestions at: Codeigniter session bugging out with ajax calls

But even with $config['sess_time_to_update'] = PHP_INT_MAX I am still seeing random logouts.

I also took the suggestions of creating class MY_Session

User's are still reporting random logouts and my logs also seem to indicate this.

EDIT: Here is my session config:

$config['sess_cookie_name']     = 'phppos';
$config['sess_expiration']      = 86400;
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = TRUE;
$config['sess_table_name']      = 'sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  = PHP_INT_MAX;

解决方案

I think you're suffering AJAX session race condition. I had the same problem, and I solved it overriding the CI session class. You have the article here:

http://www.hiretheworld.com/blog/tech-blog/codeigniter-session-race-conditions

The cleanest thing would be use a MY_Session class, in your libraries folder, and then override the methods written in the link above. Sorry for the lack of indentation, :P

class MY_Session extends CI_Session
{
    public function __construct()
    {
        parent::__construct();
    }


/*********************************************************************
 * overrides to codeigniter session library
 *
 * Handle race condition during session_id updates.
 * - Keep the old session id around in case we have to handle race
 *   conditions.
 * - Changes are marked with the string "old_session_id_changes".
 *
 * session table changes:
 * ALTER TABLE `sessions` ADD COLUMN `old_session_id` VARCHAR(40)  DEFAULT NULL COMMENT 'old session id' AFTER `user_data`,
 *  ADD INDEX `old_session_id`(`old_session_id`);
 * DELETE FROM `sessions`;
 *********************************************************************/

/**
 * Fetch the current session data if it exists
 *
 * @return  bool
 */
public function sess_read()
{
  // Fetch the cookie
  $session = $this->CI->input->cookie($this->sess_cookie_name);

  // No cookie?  Goodbye cruel world!...
  if ($session === NULL)
  {
    log_message('debug', 'A session cookie was not found.');
    return FALSE;
  }

  // Decrypt the cookie data
  if ($this->sess_encrypt_cookie === TRUE)
  {
    $session = $this->CI->encrypt->decode($session);
  }
  else
  {
    // encryption was not used, so we need to check the md5 hash
    $hash  = substr($session, strlen($session)-32); // get last 32 chars
    $session = substr($session, 0, strlen($session)-32);

    // Does the md5 hash match?  This is to prevent manipulation of session data in userspace
    if ($hash !==  md5($session.$this->encryption_key))
    {
      log_message('error', 'The session cookie data did not match what was expected. This could be a possible hacking attempt.');
      $this->sess_destroy();
      return FALSE;
    }
  }

  // Unserialize the session array
  $session = $this->_unserialize($session);

  // Is the session data we unserialized an array with the correct format?
  if ( ! is_array($session) OR ! isset($session['session_id'], $session['ip_address'], $session['user_agent'], $session['last_activity']))
  {
    $this->sess_destroy();
    return FALSE;
  }

  // Is the session current?
  if (($session['last_activity'] + $this->sess_expiration) < $this->now)
  {
    $this->sess_destroy();
    return FALSE;
  }

  // Does the IP match?
  if ($this->sess_match_ip === TRUE && $session['ip_address'] !== $this->CI->input->ip_address())
  {
    $this->sess_destroy();
    return FALSE;
  }

  // Does the User Agent Match?
  if ($this->sess_match_useragent === TRUE && trim($session['user_agent']) !== trim(substr($this->CI->input->user_agent(), 0, 120)))
  {
    $this->sess_destroy();
    return FALSE;
  }

  // Is there a corresponding session in the DB?
  if ($this->sess_use_database === TRUE)
  {
    /*
     * begin old_session_id_changes
     *
     * Search both session_id and old_session_id fields for the
     * incoming session id.
     *
     * used to be:
     * $this->CI->db->where('session_id', $session['session_id']);
     *
     * Manually create the OR condition because it causes the least
     * disturbance to existing code.
     *
     * Store the session id from the cookie so that we can see if we
     * came in through the old session id later.
     */
    $this->CI->db->where( '(session_id = ' . $this->CI->db->escape($session['session_id']) . ' OR old_session_id = ' . $this->CI->db->escape($session['session_id']) . ')' );
    $this->cookie_session_id = $session['session_id'];
    /*
     * end old_session_id_changes
     */

    if ($this->sess_match_ip === TRUE)
    {
      $this->CI->db->where('ip_address', $session['ip_address']);
    }

    if ($this->sess_match_useragent === TRUE)
    {
      $this->CI->db->where('user_agent', $session['user_agent']);
    }

    $query = $this->CI->db->limit(1)->get($this->sess_table_name);

    // No result?  Kill it!
    if ($query->num_rows() === 0)
    {
      $this->sess_destroy();
      return FALSE;
    }

    // Is there custom data?  If so, add it to the main session array
    $row = $query->row();
    if ( ! empty($row->user_data))
    {
      $custom_data = $this->_unserialize($row->user_data);

      if (is_array($custom_data))
      {
        foreach ($custom_data as $key => $val)
        {
          $session[$key] = $val;
        }
      }
    }

    /*
     * begin old_session_id_changes
     *
     * Pull the session_id from the database to populate the curent
     * session id because the old one is stale.
     *
     * Pull the old_session_id from the database so that we can
     * compare the current (cookie) session id against it later.
     */
    $session['session_id'] = $row->session_id;
    $session['old_session_id'] = $row->old_session_id;
    /*
     * end old_session_id_changes
     */
  }

  // Session is valid!
  $this->userdata = $session;
  unset($session);

  return TRUE;
}

// --------------------------------------------------------------------

/**
 * Write the session data
 *
 * @return  void
 */
public function sess_write()
{
  // Are we saving custom data to the DB?  If not, all we do is update the cookie
  if ($this->sess_use_database === FALSE)
  {
    $this->_set_cookie();
    return;
  }

  // set the custom userdata, the session data we will set in a second
  $custom_userdata = $this->userdata;
  $cookie_userdata = array();

  // Before continuing, we need to determine if there is any custom data to deal with.
  // Let's determine this by removing the default indexes to see if there's anything left in the array
  // and set the session data while we're at it
  foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
  {
    unset($custom_userdata[$val]);
    $cookie_userdata[$val] = $this->userdata[$val];
  }

  /*
   * begin old_session_id_changes
   *
   * old_session_id has its own field, but it doesn't need to go into
   * a cookie because we'll always retrieve it from the database.
   */
  unset($custom_userdata['old_session_id']);
  /*
   * end old_session_id_changes
   */

  // Did we find any custom data?  If not, we turn the empty array into a string
  // since there's no reason to serialize and store an empty array in the DB
  if (count($custom_userdata) === 0)
  {
    $custom_userdata = '';
  }
  else
  {
    // Serialize the custom data array so we can store it
    $custom_userdata = $this->_serialize($custom_userdata);
  }

  // Run the update query
  $this->CI->db->where('session_id', $this->userdata['session_id']);
  $this->CI->db->update($this->sess_table_name, array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata));

  // Write the cookie.  Notice that we manually pass the cookie data array to the
  // _set_cookie() function. Normally that function will store $this->userdata, but
  // in this case that array contains custom data, which we do not want in the cookie.
  $this->_set_cookie($cookie_userdata);
}

// --------------------------------------------------------------------

/**
 * Update an existing session
 *
 * @return  void
 */
public function sess_update()
{
  // We only update the session every five minutes by default
  if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
  {
    return;
  }

  // _set_cookie() will handle this for us if we aren't using database sessions
  // by pushing all userdata to the cookie.
  $cookie_data = NULL;

  /*
   * begin old_session_id_changes
   *
   * Don't need to regenerate the session if we came in by indexing to
   * the old_session_id), but send out the cookie anyway to make sure
   * that the client has a copy of the new cookie.
   *
   * Do an isset check first in case we're not using the database to
   * store extra data.  The old_session_id field only exists in the
   * database.
   */
  if ((isset($this->userdata['old_session_id'])) &&
      ($this->cookie_session_id === $this->userdata['old_session_id']))
  {
    // set cookie explicitly to only have our session data
    $cookie_data = array();
    foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
    {
      $cookie_data[$val] = $this->userdata[$val];
    }

    $this->_set_cookie($cookie_data);
    return;
  }
  /*
   * end old_session_id_changes
   */

  // Save the old session id so we know which record to
  // update in the database if we need it
  $old_sessid = $this->userdata['session_id'];
  $new_sessid = '';
  do
  {
    $new_sessid .= mt_rand(0, mt_getrandmax());
  }
  while (strlen($new_sessid) < 32);

  // To make the session ID even more secure we'll combine it with the user's IP
  $new_sessid .= $this->CI->input->ip_address();

  // Turn it into a hash and update the session data array
  $this->userdata['session_id'] = $new_sessid = md5(uniqid($new_sessid, TRUE));
  $this->userdata['last_activity'] = $this->now;

  // Update the session ID and last_activity field in the DB if needed
  if ($this->sess_use_database === TRUE)
  {
    // set cookie explicitly to only have our session data
    $cookie_data = array();
    foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
    {
      $cookie_data[$val] = $this->userdata[$val];
    }

    /*
     * begin old_session_id_changes
     *
     * Save the old session id into the old_session_id field so that
     * we can reference it later.
     *
     * Rewrite the cookie's session id if there are zero affected rows
     * because that means that another request changed the database
     * under the current request.  In this case, we want to return a
     * value consistent with the previous request.  Reread immediately
     * after the update call here to minimize timing problems.  This
     * should be in a transaction for databases that support them.
     *
     * Also rewrite the userdata so that future calls to sess_write
     * will output the correct cookie data.
     *
     * used to be:
     * $this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid)));
     */
    $this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid, 'old_session_id' => $old_sessid), array('session_id' => $old_sessid)));

    if ($this->CI->db->affected_rows() === 0)
    {
      $this->CI->db->where('old_session_id', $this->cookie_session_id);
      $query = $this->CI->db->get($this->sess_table_name);

      // We've lost track of the session if there are no results, so
      // don't set a cookie and just return.
      if ($query->num_rows() == 0)
      {
        return;
      }

      $row = $query->row();
      foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
      {
        $this->userdata[$val] = $row->$val;
        $cookie_data[$val] = $this->userdata[$val];
      }

      // Set the request session id to the old session id so that we
      // won't try to regenerate the cookie again on this request --
      // just in case sess_update is ever called again (which it
      // shouldn't be).
      $this->cookie_session_id = $this->userdata['old_session_id'];
    }
    /*
     * end old_session_id_changes
     */
  }

  // Write the cookie
  $this->_set_cookie($cookie_data);
}

/*********************************************************************
 * end overrides to codeigniter session library
 *********************************************************************/

这篇关于Codeigniter随机会话注销(已经尝试重写会话类并提高session_time_to_update的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆