Codeigniter storing session data in database
Due to the limitation of storing cookies in browser, we can not store bulk data in session. If we want to store more data we need to find the alternative. Codeigniter natively support storing session in database. You don’t need to do any change in code, just few configuration and it will start working fine.
Here I am sharing how you can achieve it.
To store data in Database you need a table as below:
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, PRIMARY KEY (session_id), KEY `last_activity_idx` (`last_activity`) );
This table will store your session data. Now we need to set config variable. Go to “config/config.php” and update below variable:
$config['sess_use_database'] = TRUE; $config['sess_table_name'] = 'ci_sessions';
If “sess_use_database” variable if “FALSE” make it TRUE. And if you change the table name you must tell codeigniter to use that table by setting the varibale “sess_table_name” or just uncomment this line.
That set… Now you are ready to go.
You don’t need to set any cronjob/scheduler to remove expire session from table, codeigniter session class will take care it.