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.
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
$this->load->library('session'); before use it.
First create a database table:-
CREATE TABLE IF NOT EXISTS `ci_sessions` ( `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.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.