php - 为什么在 CodeIgniter 中调用 sess_update?

标签 php codeigniter

为什么在 CodeIgniter 中根本需要更新 session ID。我知道您可以控制在配置中更新 session ID 的频率。但是为什么他们每 5 分钟(默认情况下)更改一次 session 的 ID?

为什么 session 不能创建一次并且在 session 过期之前使用相同的 ID?

更新session的函数在这里:

/**
 * Update an existing session
 *
 * @access  public
 * @return  void
 */
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;
    }

    // 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 = '';
    while (strlen($new_sessid) < 32)
    {
        $new_sessid .= mt_rand(0, mt_getrandmax());
    }

    // 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
    $new_sessid = md5(uniqid($new_sessid, TRUE));

    // Update the session data in the session data array
    $this->userdata['session_id'] = $new_sessid;
    $this->userdata['last_activity'] = $this->now;

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

    // 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];
        }

        $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)));
    }

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

最佳答案

这是出于安全原因,以防止欺骗。 session 已加密并存储在您的 Cookie 中。任何人都可以复制您的 Cookie 并转到另一台 PC 并登录。

假设 session 不会过期。这意味着,如果我在您的 PC 上窃取了您的 cookie,我可以从任何地方登录,因为我在 Cookie 中加密了您的 session ID。如果框架每 5 分钟更新一次 session ,这几乎不可能发生。

如果您不喜欢它的工作方式,您可以随时通过扩展 Codeigniter 核心系统的库来为 session 创建自己的库。尽管不建议这样做。

关于php - 为什么在 CodeIgniter 中调用 sess_update?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12789347/

相关文章:

php - 如何配置Codeigniter报告所有错误?

mysql - 如果数据为空,则按日期分组 Mysql 返回 0

mysql - 如何在 CodeIgniter 中有条件地使用不同的数据库

php - 如何将数组分配给sql查询的变量

php - 如何检查一个类的对象是否已经存在于 PHP 中?

跨类的 PHP 日志记录方法

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

javascript - 显示多个标记、变量和数组问题

php - PHP (CodeIgniter) 文件下载中的空行

php - 关于显示特殊字符的建议