Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is session destory not enough to clean the session

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.

like image 846
Kamo Avatar asked Nov 25 '25 21:11

Kamo


2 Answers

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

like image 200
Michael Mrozek Avatar answered Nov 28 '25 11:11

Michael Mrozek


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

like image 36
duckbox Avatar answered Nov 28 '25 10:11

duckbox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!