Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use Database Sessions or Native PHP File Sessions?

I've just moved over from my own MVC framework to a community supported one (CodeIgniter). I'm just converting my sessions over to the CodeIgniter functions and am noticing that they, by default, store the session data in an encrypted cookie. The alternative they offer are database sessions but not server-side file sessions like the native PHP library.

Now on my site, I will be building a secure backend panel so an encrypted cookie doesn't seem like the smart option but I don't particually want to have to connect to my database unnecessarily as it's not very fast (shared hosting).

I'm wondering what the reasoning behind them not supporting native sessions would be and whether database sessions or server-side file sessions are generally regarded as the better option.

Thanks.

like image 572
Ryall Avatar asked Feb 03 '23 07:02

Ryall


1 Answers

Basically, to store the session's data, people generally use one of three solutions :

  • files (the default)
  • database
  • memcached

Files is the most used, as it's the default -- and it works perfectly fine in most cases -- but there's at least one situation in which it doesn't work : when you have several servers, and your users are load-balanced on those (i.e. when 1 user is not always on the same server).

In that kind of situation, having a central/shared place to store the sessions is necessary -- and databases fit that description ; and are easy to setup, too -- and PHP applications generally work with a database.

And as databases don't scale that well, especially for writes, you sometimes use, instead, something like memcached : a mecanism that stores data in RAM (faster), accross as many servers as you want/need (scales well).


What solution should you use ?

Well, in which of those situations are you ?

  • Files are OK, at least as long as one user is always on the same server
  • If you need a database for your application, you can store sessions in the database : no need for any additionnal setup (For example, Drupal does this, by default).
  • memcached needs more setup, but is probably the best solution if you have really heavy traffic...
like image 87
Pascal MARTIN Avatar answered Feb 05 '23 21:02

Pascal MARTIN