Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing user data in sessions - from DB

If I have a login system or something similar, I store a session_id and a user_id in sessions, but any other data pertaining to a certain user is stored in a database. I've seen other scripts where people store other data (username, email etc) in sessions.

I was just wondering, which would be "better"? Saving data in sessions from the DB or having less sessions and grabbing the data from the database?

Thanks!

like image 533
Prash Avatar asked Nov 06 '12 17:11

Prash


2 Answers

You can store whatever information you like in the $_SESSION. I believe it can be up to 128Mb - limit is governed by memory_limit which is 128Mb by default. You could change this.

However, as a rule of thumb, I'd store information that is pertinent and/or less expensive than querying a database for - Put another way as little as possible.

It will no-doubt vary widely by use, but often, sessions contain things like:

  • Username
  • Full display names
  • Email address
  • Id's (user or otherwise)
  • Permissions
  • User groups
  • Hashes
  • Form input errors (temporarily, to highlight form errors)

Storing large blocks of data/info isn't advised though for reasons of speed/scale.

If your site/platform needs to scale at a later date, at the right point, you'd be better off looking at write-through caching or similar for frequently used/required data (e.g. Memcached) and storing the vast majority of data in your DB - where is should be.

Hope this helps.

like image 78
nickhar Avatar answered Sep 29 '22 01:09

nickhar


The answer is it depends and in your case, it probably doesn't even matter.

Session approach

  • Less queries = faster

DB approach

  • Less data in session prevents clobbering
  • Updates to the DB are reflected immediately without having to worry about simultaneously updating the session
like image 24
Explosion Pills Avatar answered Sep 29 '22 02:09

Explosion Pills