Why is it good save to save sessions in the database? Why is it good save to save sessions in the database? codeigniter codeigniter

Why is it good save to save sessions in the database?


It doesn't improve security in any way.

The most common and reasonable pattern to store sessions in database is when you have several frontend servers, so you need a shared session storage for them.

For downvoters: a file in filesystem isn't less secured than a record in database.


The idea is that sessions can't be hijacked.

A session ID is stored in a cookie. If a hacker can steal that ID, he can pretend to be someone else, because a session is identified by... it's ID.

By saving a user's session ID, IP and agent server-side (your database for example) you can compare the data saved in the database with the client. If a hacker steals someone's session ID, the hacker just might not have a matching IP and/or user-agent, making the users not match which allows you to show or hide certain content.

You have to compare the data manually though.


A common security faux-pas with file-based sessions is to store them in /tmp or another shared directory where the data may be accessible to 3rd parties; especially on shared hosts this can be a problem. This can be prevented with proper file permissions though.

Storing them in a database means you have all the access restrictions of the database in place, though that also means you need to configure them correctly and set up the physical storage of the database securely.

It improves performance insofar as the database server has more layers to improve performance through caching and in-memory storage, whereas file based sessions always incur a disk access. Concurrent access can be improved since you can choose other concurrency mechanisms than file locking. If your database server is already busy with regular database work though, additionally throwing session handling at it may or may not be a good idea.