user3425506
user3425506

Reputation: 1437

Session storage vs non-session storage in PHP

As part of an effort to implement username / password authentication for websites, I am using PHP sessions. I read a very interesting article called PHP Sessions in Depth

One thing that was not addressed in the article (as it was not for novices like me) is why data would be stored in the session as opposed to a non-session database other than for the reason of knowing which user the session is for.

For example the following is given as an example of data that might be in session storage:

[ "theme" => "blue", 
  "volume" = >100]

The article goes on to discuss race conditions which can result when a large amount of this type of data is being changed in session storage. What I want to know is why not just store it in a non-session storage database along with the user's ID. Only the user's ID would also be stored in session storage so it would persist between http requests? I have taken the latter approach but my websites are very simple and I am wondering if I might run into problems if they become more complex.

Upvotes: 0

Views: 85

Answers (1)

IMSoP
IMSoP

Reputation: 97658

You are absolutely correct. Storing too much data directly in a session can cause multiple problems:

  • Performance, since PHP serialises the entire season to a string when saving, and unserialises the whole thing on next page load
  • Stale data, if the session isn't the "source of truth" for some information, just an extra copy of data retrieved from somewhere else, like a primary database

Race conditions as such are not generally an issue with sessions as designed, because they are intended to be "locked" for the entire duration of a request. If the same user makes two requests at once, the second one just waits for the first to complete and unlock the session. However, if you write your own session handler that doesn't lock, or make heavy use of session_start and session_write_close, you won't have that guarantee.

The main reason for putting extra data into the session is to use it as a sort of cache: if every single page says "Hello $username" at the top, storing the username as well as the ID in the session saves you a round trip to the database to fetch it every time. So there is a balance to be found, and you can't 100% say that storing the absolute minimum is always optimal.

Upvotes: 1

Related Questions