Saving Session Data to a Database in CodeIgniter3

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:-

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:

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.

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets. Protection Status