发送ajax请求时避免重置会话超时



如果通过ajax向特定控制器函数发出后请求,是否可以告诉codeigniter跳过会话超时重置。我经常在用户登录面板中调用ajax来检查一些东西,但这些调用可以保持会话的有效性,因此即使用户保持10分钟(sess_expiration时间(的非活动状态,会话也不会被终止,他们仍然永远保持登录状态。

如果(并且只有If(您的Ajax调用是完全与会话无关的(也就是说,它不需要登录才能运行,也不需要来自用户的任何会话数据等(,您可以从一个单独的Ajax特定控制器提供Ajax请求,然后在使用该特定控制器时禁止会话库自动加载。

如果ajax调用需要一个已登录的用户,那么你就太倒霉了。

但是,如果您满足这些条件,请在application/config/autoload.php中找到$autoload['libraries]部分并使用此肮脏的破解:

// Here, an array with the libraries you want/need to be loaded on every controller
$autoload['libraries'] = array('form_validation');
// Dirty hack to avoid loading the session library on controllers that don't use session data and don't require the user to have an active session
$CI =& get_instance();
// uncomment the one that fits you better
// Alternative 1: you only have a single controller that doesn't need the session library
// if ($CI->router->fetch_class() != 'dmz') array_push($autoload['libraries'], 'session');
// END alternative 1
// Alternative 2: you have more than one controller that doesn't need the session library
// if (array_search($CI->router->fetch_class(), array('dmz', 'moredmz')) === false) array_push($autoload['libraries'], 'session');
// END alternative 2

在上面的代码中,dmzmoredmz是我想象中的两个控制器名称,它们需要不加载会话库。只要不使用这些,session库就会被推入自动加载,从而被加载。否则,session库将被忽略。

事实上,我在我的一个网站上运行了这个程序,以便允许负载平衡器的健康检查运行(在每个应用程序服务器上,每5秒运行一次,来自主负载平衡器及其备份(,并用无用的数据填充我的会话表,工作起来很有魅力。

不确定您使用的CI版本,但上面的代码已在CI 3.1.11上进行了测试。

现在,正如您所说的Ajax调用需要会话驱动程序,唯一的解决方法就是稍微扰乱会话驱动程序本身。在3.1.11中,会话驱动程序位于system/libraries/Session/Session.php中,您需要更改的部分是构造函数方法的最后部分(从第160行开始(。对于这个例子,我假设您的Ajax调用是由一个名为"的特定控制器处理的;Ajax";

// This is from line 160 onwards
elseif (isset($_COOKIE[$this->_config['cookie_name']]) && $_COOKIE[$this->_config['cookie_name']] === session_id())
{
$CI =& get_instance();
$new_validity = ($CI->router->fetch_class() !== 'ajax') ? time() + $this->_config['cookie_lifetime'] : $_SESSION['__ci_last_regenerate'] + $this->_config['cookie_lifetime'];
setcookie(
$this->_config['cookie_name'],
session_id(),
(empty($this->_config['cookie_lifetime']) ? 0 : $new_validity),
$this->_config['cookie_path'],
$this->_config['cookie_domain'],
$this->_config['cookie_secure'],
TRUE
);
}
$this->_ci_init_vars();
log_message('info', "Session: Class initialized using '".$this->_driver."' driver.");

简而言之,这个例子(还没有测试过,所以在部署它之前请先测试一下,它可能有一两个拼写错误(将首先实例化CI核心,并从路由器中获取控制器名称。如果它是一个常规控制器,它将把新的cookie有效性确定为"0";现在加上来自配置的cookie有效性;。如果是ajax控制器,cookie有效性将与当前有效性相同(上次再生时间加上cookie有效性…必须根据三元运算符的要求重申(

然后,根据_config['cookie_lifetime']的值,修改setcookie以使用预先计算的cookie有效性

最新更新