title: Persistent login using cookies and session variables
body: <p>I've been researching the best (and safest) ways to implement persistent logins on my website, and I've come up with the following:</p>
  
  <p>When a user logs in, a cookie is created containing the user's ID/username, and a randomly generated number (token). The token is stored in a relational table along with the user ID/username. Every time a members-only page is loaded, this cookie is checked against the relational table, and if it exists <em>and</em> matches with the token, the login is valid and the page can load. If not, however, then the login is invalid, the cookie is destroyed, and the  user is prompted to log in.</p>
  
  <p>I was thinking... to save on database access every single time a page is loaded, I could also have a session variable that lasts, say, 10 minutes, and is destroyed automatically when the browser closes. If the session is alive, then it's refreshed and the user can proceed. If the session expires, but the cookie is still valid, check the cookie, reset the token, store that new token in the database (while eliminating the old token, or storing it in an archives table for future reference), and reset the cookie using the new token value.</p>
  
  <p>However, what would the session contain? And how could the session not simply be faked with some JavaScript? Perhaps the session contains a one-way encrypted hash? What would be used to generate that hash (user ID, etc.)?</p>
  
  <p>I'm kind of stuck on where to go from here. I get the cookie stuff, but using temporary sessions (to avoid repeated calls to the database every single time a page is loaded) eludes me. Any help? Thanks.</p>