title: Expiring Custom PHP Session when browser closes
body: <p>I'm building a custom PHP Session handler using MySql, and I've been struggling with something. After a throughout (or not so much, subject to personal opinion) search in Stack Overflow, I couldn't find an answer to my question: most just answer how to expire a session in the client-side, but this question is focused on the server-side.</p>
  
  <p>The issue is the following: I store the session data on a SQL database, and send an id of the session as a cookie (basic session handling); <em>if</em> the user selected not to be remembered (aka keep me logged on/remember me) the cookie should expire on the event of the browser closing, but for obvious reasons it wouldn't expire on the database (this is not intended, but it's pretty hard to tell when a browser closes from the server side); moreover, <em>if</em> the user selected to be remembered, the cookie shouldn't expire, and the user should be signed in automatically when he starts the browser again.</p>
  
  <p>What I would like to do is <strong>expire the session on the database when the browser is closed (if the user doesn't select remember me),</strong> and to <strong>keep the session alive in both ends if the user selects remember me, but assign the user a new session if he logs in again (and unset/delete the previous one).</strong></p>
  
  <p>All for the sake of security, I absolutely want to void the sessions that won't be used again; for example, when the user closes the browser, the cookie is deleted and the session won't be accessed ever again legitimately by the corresponding user, so it should be deleted.</p>
  
  <p>My current idea is to use double sessions: having two cookies with two different ID's and cookies, in which one of the cookies would expire when the browser is closed and one would remain, and the latter would be used to reference the primary one, delete it, and generate a new one and logging in the user back to the new one (if the user selected to be remembered). The double sessions don't necessarily need two databases, as they could just be stored on the same table with different fields.</p>
  
  <p>My main focus is to keep the database clean and the system safe. <strong>How would you manage session expiration on the server side?</strong></p>