Storing user data in sessions - from the database

If I have a login system or something like that, I store session_id and user_id in sessions, but any other data related to a specific user is stored in the database. I saw other scripts in which people store other data (username, email address, etc.) in sessions.

I'm just wondering what would be β€œbetter”? Saving data in sessions from a database or fewer sessions and capturing data from a database?

Thanks!

+4
source share
3 answers

You can save any information you like in $_SESSION . I believe that it can be up to 128 MB - the limit is determined by memory_limit , which is 128 MB by default. You can change that.

However, as a rule, I would like to store information that is relevant and / or less expensive than a database query - Put another way as little as possible .

This will not doubt the wide range of uses, but often sessions contain things such as:

  • Username
  • Full Screen Names
  • E-mail address
  • Identifier (user or other)
  • Access rights
  • Groups of users
  • Hash
  • Form input errors (temporarily to highlight form errors)

Storage of large blocks of data / information is not recommended, although for speed / scale reasons.

If your site / platform needs to be scaled at a later date, in the right place, you will be better off looking through pass-through caching or similar for frequently used / required data (for example, Memcached ) and store the vast majority of data in your database - where it should be.

Hope this helps.

+2
source

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

Session Approach

  • Fewer queries = faster

DB approach

  • Less data in the session prevents merging
  • Database updates are immediately reflected without worrying about updating the session at the same time.
+3
source

Practice shows that it is better to store data in a database (for> = medium-sized projects (server farm / really a lot of data in a session) or to increase security for any type of project (for example, for shared hosting)). Even the user ID should not be stored in $_SESSION . Hashes, flash messages, quick settings are what should be in $_SESSION .

But if you still have the question "Do I need to save a session in the database", then most likely you should not store it in the database.

+2
source

Source: https://habr.com/ru/post/1444420/


All Articles