Click to See Complete Forum and Search --> : sessions vs cookies vs mysql


charlesdavison
12-08-2004, 04:08 PM
I've set up a MySQL database with a registration and logon area. Login is set up using sessions and is, basically, working.

What I want to do is have the user effectively logged in for a long time (so that if they come back in a few weeks/months they are remembered and logged in).


My first question is:

1. Should this be set as a session cookie with the validity set for a long time or should I set a separate cookie?

The reason I ask is because I was wondering if having loads and loads of sessions open affects performance. Using a separate cookie no data would be stored on the server unless the user was actually using the site at the time.


The other question:

2. Some data will be displayed on each page the user sees. I could access the database every page to retrieve that but it isn't that important that the data is up-to-the-minute accurate. So should I instead store the data in a cookie or session variable and have it updated every 2 hours or so? Would this be greatly preferable to accessing the same data on the database every time?


Sorry about the length of this post, but any opinions & explanations why are greatly appreciated.

compbrat75
12-17-2004, 11:25 PM
Hi charlesdavidson,

Both situations have up and down sides to them. I think the cookie is the best solution. Since you can't determine when the user will return to the site, I'd create and store the session in the MySQL database and store the session info in a cookie, but I'd expire the session and cookie after a reasonable amount of time. After all, users from time to time delete all of their cookies. You could reset the expiration date of the cookie each time they visit the site to keep it from expiring. If you add a timestamp column in your MySQL database with the stored session, you can periodically remove extremely old and untouched sessions. The timestamp would automatically update each time the session was accessed so you don't need to worry about deleting an actively used session. Just make sure that you have the session update at some point during their site visit.

As for you second question, I suggest storing the most commonly displayed information in the session hash. Then when they open other pages on the site, those pages can check to see if that data exists in the session hash. If it doesn't it accesses the database and stores it, if it does, then it displays it. You could write a check into the script that if the session's timestamp is x number of hour/days old, it needs to visit the database to get the latest data.

Hope some of this helps. :)
compbrat75