Codeigniter session bugging out with ajax calls Codeigniter session bugging out with ajax calls codeigniter codeigniter

Codeigniter session bugging out with ajax calls


Try this

<?php/** * ------------------------------------------------------------------------ * CI Session Class Extension for AJAX calls. * ------------------------------------------------------------------------ * * ====- Save as application/libraries/MY_Session.php -==== */class MY_Session extends CI_Session {    // --------------------------------------------------------------------    /**     * sess_update()     *     * Do not update an existing session on ajax or xajax calls     *     * @access    public     * @return    void     */    public function sess_update()    {        $CI = get_instance();        if ( ! $CI->input->is_ajax_request())        {            parent::sess_update();        }    }}// ------------------------------------------------------------------------/* End of file MY_Session.php *//* Location: ./application/libraries/MY_Session.php */

The problem is in the sess_update function of the session class, that generates a new session_id after X seconds. Every page have a session_id, if the session_id expires before the ajax call is made, that call will fail.

Create a php file in /application/libraries/ with the name MY_Session (or whatever prefix you set), paste this code there and that is all.This function will override the sess_update function in the session class, checking on every request if that request was made by ajax, skipping the sess_update function.

Its a bad idea set the sess_expiration at higher values. This is a security feature that will protect you against session hijaking

PD: i'm not very fluent in english, if you dont understand something just let me know.


Until it is merged into the stable branch, the solution (finally!) is to use Areson's commit 245bef5 combined with the database schema:

CREATE TABLE IF NOT EXISTS  `ci_sessions` (    session_id varchar(40) DEFAULT '0' NOT NULL,    ip_address varchar(45) DEFAULT '0' NOT NULL,    user_agent varchar(120) NOT NULL,    last_activity int(10) unsigned DEFAULT 0 NOT NULL,    user_data text NOT NULL,    prevent_update int(10) DEFAULT NULL,    PRIMARY KEY (session_id),    KEY `last_activity_idx` (`last_activity`));

For more information, read pull 1283 comments top-to-bottom.


We had this problem, it was due to the sess_time_to_update parameter in config.php. CI use this to update the session ID to a new one. If the change happen in an ajax call, CI sends a new cookie to tell the browser the new session ID. Unfortunatly, browsers seems to ignore this cookie and keep the old session ID.

We fixed it by setting the sess_time_to_update to sess_expiration in the config.

$config['sess_time_to_update'] = $config['sess_expiration'];