When creating a web application, and lets say you have a User object denoting a single user, what do you think is the best way to store that the user has logged in?
Two ways I’ve thought about have been:
- Stored the user database id in a session variable
- Stored the entire user object in a session variable
Any better suggestions, any issues with using the above ways? Perhaps security issues or memory issues, etc, etc.
I recommend storing the id rather than the object. The downside is that you have to hit the database every time you want to get that user’s information. However, unless every millisecond counts in your page, the performance shouldn’t be an issue. Here are two advantages:
If the user’s information changes somehow, then you won’t be storing out-of-date information in your session. For example, if a user is granted extra privileges by an admin, then those will be immediately available without the user needing to log out and then log back in.
If your session information is stored on the hard drive, then you can only store serializable data. So if your User object ever contains anything like a database connection, open socket, file descriptor, etc then this will not be stored properly and may not be cleaned up properly either.
In most cases these concerns won’t be an issue and either approach would be fine.