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.

Leave a Comment