Improved database table structure for CodeIgniter sessions

I had a problem where CodeIgniter sessions stored in the database were creating multiple session_id’s (each time the session library was called) for the same user.

Here is how my session configuration is defined…

$config['sess_cookie_name']        = 'my-session';
$config['sess_expiration']        = 60*60*2; //2 hours
$config['sess_expire_on_close']    = TRUE;
$config['sess_encrypt_cookie']    = FALSE;
$config['sess_use_database']    = TRUE;
$config['sess_table_name']        = 'sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent']    = TRUE;
$config['sess_time_to_update']    = 300;

Here is the updated table structure…

CREATE TABLE IF NOT EXISTS `sessions` (
  `session_id` varchar(32) NOT NULL default '0',
  `ip_address` varchar(16) NOT NULL default '0',
  `user_agent` varchar(255) NOT NULL,
  `last_activity` int(10) unsigned NOT NULL default '0',
  `user_data` text NOT NULL,
  PRIMARY KEY  (`session_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

My solution… First, I increased the user_agent field to 255 characters in length. Then, since session_id is always 32 characters in length, I reduced that from 40. If you have any other suggestions, feel free to leave a comment.

Hope this helps someone else having the same problem with CodeIgniter sessions that are being stored in the database 🙂

One thought on “Improved database table structure for CodeIgniter sessions”

  1. Another important note…

    Some versions of Internet Explorer have a problem interpreting cookie names with underscores in them. I suggest using hyphens or CamelCased cookie names to avoid that issue 😉

Leave a Reply

Your email address will not be published. Required fields are marked *