Killing old sessions

I was messing with sessions and noticed that if I just closed my browser, it didn’t destroy them.

If I clicked on Log out, it destroyed that session.

I have a /tmp directory I put my sessions into. The reason I started pondering sessions was when I was tinkering with users and saw the session numbers were being held over from one user to the next.

I went to /tmp and saw a whole listing of old sessions that seemed to be contaminating the newer ones.

This is what I have been using:


// Unset all of the session variables.
  $_SESSION = array();
 
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
  if (isset($_COOKIE[session_name()])) {
            setcookie(
            session_name(),
            '',
            time()-42000,
            '/'
            );
  }
 
// Finally, destroy the session.
  session_destroy();

Here’s what I do to kill / restart a session (e.g. to log out):


session_unset();
session_start();
session_regenerate_id(true);
$id = session_id();
Cookie::setParameter("PHPSESSID", $id, 1);

Unset kills all existing session variables.
Start ensures a session is started
Regenerate ID forces a new session id to be set (the true param forces the old session file to be deleted)
Cookie::setParameter sets the PHPSESSID cookie to the new ID of the session. (It’s an internal class of mine… you know how to set cookies otherwise)