1 回答

TA貢獻1865條經驗 獲得超7個贊
如果(且僅當)您的 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 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 有效性為“現在加上配置中的 cookie 有效性”。如果是ajax控制器,則cookie有效性將與當前有效性相同(上次再生時間加上cookie有效性..必須重申,因為三元運算符需要它)
然后,setcookie根據該值進行修改以使用預先計算的 cookie 有效性_config['cookie_lifetime']。
- 1 回答
- 0 關注
- 198 瀏覽
添加回答
舉報