Andy Haskell
Andy Haskell

Reputation: 717

How do I kill a PHP session?

I am writing a social networking site, and I am trying to figure out PHP sessions. At the top of the login page, I call session_destroy(), and I call session_start() at the page where new users are officially registered as users and at the user homepage. When a user logs out, they are linked to the home page that has session_destroy, but then I can log back in as whatever user just logged out, no matter what username or password I enter. This is my first time working with sessions, so I'm wondering where I'm supposed to put session_destroy so it actually destroys the session when I logout.

Upvotes: 3

Views: 6639

Answers (2)

Mac
Mac

Reputation: 1566

The best way is by following the manual. Here is sample code that erases any session variables, the session cookie and then the session file itself:

<?php

// Unset all of the session variables.
$_SESSION = array();

// Delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if( ini_get( "session.use_cookies" ) ) {
    $params = session_get_cookie_params();

    setcookie(
      session_name()
      , ''
      , time() - 42000
      , $params[ "path"     ]
      , $params[ "domain"   ]
      , $params[ "secure"   ]
      , $params[ "httponly" ]
    );
}

// Finally, destroy the session.
if( session_status() === PHP_SESSION_ACTIVE ) { session_destroy(); }

Upvotes: 0

Gumbo
Gumbo

Reputation: 655659

Use session_destroy to destroy the session data and session_unset to clear the $_SESSION variable respectively.

Furthermore, call session_regenerate_id(true) after an authentication attempt to change the current session’s ID and destroy the session data that is still associated to the old session ID.

Upvotes: 5

Related Questions