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

如果 post 请求通过 ajax 发送到特定的控制器功能,是否可以告诉 codeigniter 跳过会话超时重置。我在用户登录仪表板内频繁进行 ajax 调用来检查某些内容,但这些调用使会话保持活动状态,因此即使用户在 10 分钟(sess_expiration 时间)内保持不活动状态,会话也不会被终止,并且它们仍然永远保持登录状态。



慕尼黑5688855
浏览 90回答 1
1回答

莫回无

如果(且仅当)您的 Ajax 调用完全与会话无关(即,不需要登录即可运行,不需要来自用户的任何会话数据等),您可以提供 Ajax 请求来自单独的特定于 ajax 的控制器,然后在使用该特定控制器时禁止会话库自动加载。如果 ajax 调用需要登录用户,那么您就很不幸了。但是,如果您满足这些条件,请找到该$autoload['libraries]部分application/config/autoload.php并使用这个肮脏的技巧:// 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在上面的代码中,dmz和moredmz是我的两个虚构的控制器名称,需要不加载会话库。每当不使用这些库时,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 onwardselseif (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 有效性为“现在加上配置中的 cookie 有效性”。如果是ajax控制器,则cookie有效性将与当前有效性相同(上次再生时间加上cookie有效性..必须重申,因为三元运算符需要它)然后,setcookie根据该值进行修改以使用预先计算的 cookie 有效性_config['cookie_lifetime']。
打开App,查看更多内容
随时随地看视频慕课网APP