Tag Archives: Sessions

Codeigniter Session Storage Alternative Method

The limit of a cookie is 4kb. If you choose to store codeigniter session data in the cookie then you should not exceed 4kb.

To store more than 4kb of session, you can set in config.php file with the following setting:

$config['sess_use_database']	= TRUE;

This allows you to store session data in database.

Refer to http://ellislab.com/codeigniter/user-guide/libraries/sessions.html on how to setup saving session data to database.

Alternative Method

An alternative method to store large session data without using database is to use CodeIgniter file-cache. This allows you to store session data into a file located in CodeIgniter cache folder.


function login(){

    /* Do your user login validation here */
    $user_id = $this->myusermodel->verifyLogin();
    $this->session->set_userdata('users_id', $user_id);
    /* End of login validation */

    $session_data = $this->mymodel->get_my_big_data(); 
    $cache_user = array();
    $cache_user["session_data"] = $session_data;
    $this->cache->file->save('cu-' . $user_id, $cache_user, 100000000);

From example above, i store only the $user_id into the session and the rest into a cache file in the server. The cookie / session is now very small as it contains $user_id only.

Then, I save session data into a cache file. To ensure I am able to access the correct cache file when I want to retrieve the session data, I use ‘cu-‘ + $user_id  as the key. Note that the time-to-expire is set to unlimited as the data need to be used all the time.

About CodeIgniter Cache Library: http://ellislab.com/codeigniter/user-guide/libraries/caching.html#file

To retrieve session data:

function loadCache(){
    $cache_id = 'cu-' . $this->session->userdata('users_id');
    $cache_user = $this->cache->file->get($cache_id);
    $session_data = $cache_user["session_data"];

    //Perform operation on $session_data here.

To retrieve session data, simply call $this->cache->file->get($cache_id). The returned object is exactly what has been saved.

Note: To ensure the safety of the cached data, ensure you put the cache folder outside of WWW or use .htaccess to disable access to any files in cache folder.

To change the location of the cache folder, modify the following in config.php file:

$config['cache_path'] = '/mydrive/safefolder/cache'; //Ensure this folder is writable by apache

Good luck on the implementation and have fun.