Storing user session variables in file vs in database

Alan Beats picture Alan Beats · May 25, 2011 · Viewed 14.7k times · Source

I've got a php application and I'm saving the session variables for the user using $_SESSION itself. Is there any particular advantage of storing it in a database?

I'm looking for a reliable / well-researched article which talks more about this. I havent been able to locate anything yet.

Answer

Etienne Marais picture Etienne Marais · May 25, 2011

The advantage you have of storing it in a database is that the data exists as long as you want it to exist.

Your browser will destroy the session according to how it is setup, which makes it a bit unreliable. I can't however find an article on this yet but this is what I use as a convention for a situation like this.

Any data that needs to be stored long term, like user details and activity I store in a database. Any data that is only relevant to the current workspace, like logging into a site and posting a few comments etc. can be stored in the session. For instance I store user authentication details in a session to constantly check whether the user is logged in or not and whether to redirect him/her to the correct page.

This works wonders when checking access rights throughout your application.

For me its much safer to store user details in a database because it cannot be publically accessed like the $_SESSION.

Please disagree with me if you want to though.