views:

45

answers:

2

When the user clicks a logout button, I connect to a script that simply does this

session_destroy();
session_start();

I thought this would be enough to reset all $_SESSION variables such as $_SESSION['logged'] and $_SESSION['username'] but when I load the page again, it automatically logs me in as if the session is still active.

+1  A: 

Surely you would just have $SESSION_DESTROY(); on its own, without $SESSION_START(); within the logout page ?

duckbox
You can't even do that, PHP emits `Warning: session_destroy(): Trying to destroy uninitialized session`. And it wouldn't fix his problem anyway
Michael Mrozek
My bad, should have said he has them back to front.
duckbox
+5  A: 

As the documentation explains:

It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

It also gives an example of how to do so:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// 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 (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.
session_destroy();
?>

Just clearing the array is sufficient to log the user out; they'll still have the same session ID, but $_SESSION will be empty, so $_SESSION['logged'] and $_SESSION['username'] won't exist

Michael Mrozek
Thanks Michael, that did it.
Kamo