Reputation: 5619
I'm doing a practice project in PHP (making a forum), and trying do decide on a mechanism to keep a user logged in. I've created a user class, through which a user is authenticated (on sign in) and all future user account related operations will be through that class (i.e user related info retrieval, when a user makes a post/comment, etc).
To keep a user logged in, the easiest path seemed to be to use sessions and store the user object in a session (not cookies since that would be a security risk), but after doing some research I found out that sessions can put a huge load on a system, specially if large amounts of data is saved in them.
After trying to figure out a solution for this I came up with two alternatives:
Put only the user ID in the session, and through the user ID remake the user object each time. However again this would seem to be a bad implementation since the database will have to be re-queried each time.
Save the user ID in the session (once the user has successfully logged in ofcourse), and save the whole object in a cookie, and each time before using the cookie, authenticate the cookie by matching the user ID in session with the user ID in cookie. I'm not quite sure how cookies work, but since some critical user info may be stored in the user object (hence the cookie), is there some kind of security risk here? Can cookies be stolen?
Is there another alternative which is better? Whether it be a different way to use sessions or cookies, or to use some method completely different from session and cookies?
Upvotes: 0
Views: 845
Reputation:
I would go for:
- Put only the user ID in the session, and through the user ID remake the user object each time. However again this would seem to be a bad implementation since the database will have to be re-queried each time.
and turn on MySQL query cache which will make your frequent queries much faster.
I don't recommend $_SESSION
if your data is huge (but how big is this data actually?)
Upvotes: 1
Reputation: 3200
At the begining You should forget about 2. option. It's very dangerous to save critical data in cookie.
First Option is much better. You need to choose: data in $_SESSION or in database. If it's large object, you can serialize them and send into blob field in database. Or another idea: Save serialized data in file, then you can avoid additionel queries. But offcourse there is another problem: many IO file operations.
Think about this, test some options and then you should be able to choose best option for You.
Upvotes: 1