When handling user authentication in PHP with sessions, I see two main options for accessing the user’s properties after successfully logging in:
- Load the user’s main properties into the session superglobal
- Load only the user’s UID (username or id # etc) into the session e.g.
$_SESSION['username'], then fetch the user’s main properties on page load and store these in a user object
Method 1
- Scope is more easily accessible through the session superglobal
Method 2
- You don’t have to worry about updating the session variables when the user’s data is modified, since you’re fetching it on each page
My questions
- Am I overlooking other options?
- What is generally the “done” way?
- What about performance? Which method will be quicker under which circumstances?
Notes
-
When I say the user’s “main” properties, I refer to those which will be used on many pages, such as the user’s name, access level, email address etc. Obviously you wouldn’t load too large an amount of data.
-
I am referring to database-stored sessions and not file-based.
Usually, only the UID or any other unique identifier (e.g. the username) is stored because all other data could be changed dynamically.
However, it depends on the data and the project itself. Loading e.g. access level, username and email as you said in addition to the UID could be highly efficient if those data is used often and you really care about updating them!
On the other hand, only storing the UID is inefficient because you have to request all data on each page but it’s a more secure approach. Anyway, if you need to load further user data on most pages, this approach would be the better one because you have to request data anyway.
Nevertheless, to increase the efficiency of e.g. database request you could use a database cache. If you do so, the efficiency of both ways may be nearly equal.
In short, it really depends on the type of project, needed data and environment which approach is the better and more efficient one.
Please be also aware that if you store user data other than the UID you need to save session IDs too because a user could open more than one session and you need to make sure that he changes the same session if he changes user data!