Skip to content

Saving Session Data to a Database in CodeIgniter3

Last updated on May 6, 2018

CodeIgniter natively support storing session in the database. You do not need to do any changes in code, just a few configurations and it will work.

Storing session data in the database will increase the security of the application. Because when you have session data in the database, every time a valid session is found in the user’s cookie, a database query is performed to match it. If the session ID does not match, then the session is destroyed. Without storing sessions in the database there is a chance of restoring the old session by modifying their cookies. Because a session id is stored in a cookie, so with that ID, the hacker can pretend to be someone else, because a session is identified by its ID.

Saving Session Data to a Database in CodeIgniter3

Session IDs can never be updated, they can only be generated when a new session is created.

Remember don’t forget to load session library via autoload.php or $this->load->library('session'); before use it.

First create a database table:-

        `id` varchar(40) NOT NULL,
        `ip_address` varchar(45) NOT NULL,
        `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
        `data` blob NOT NULL,
        KEY `ci_sessions_timestamp` (`timestamp`)

Once you have created your database table you can enable the database option in your config.php and also specify the table name if it differ as follows:

$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_sessions';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions'; //It is your table name name
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;

Once enabled, the Session class will store session data in the DB.

One more advantage of storing session data in the database is, you can sync user sessions across multiple servers on heavy load times. Normal sessions are saved to files on disk. If it is behind a load balancer, it is not an easy way to sync these files across multiple servers effectively without losing sessions.

0 0 votes
Article Rating
Notify of

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments