Question Overflow
Question Overflow

Reputation: 11255

Session taking its own sweet time to be Destroyed

I have created a user page with a menu that contains a logout button. Upon clicking the button, the user is directed to a logout page with the following code:

session_start();
session_destroy();

include("/var/www/include/header.inc");
echo "<h>Logout Success</h>";
include("/var/www/include/menu.inc");
include("/var/www/include/footer.inc");

The code in the menu.inc file is written such that:

if(@$_SESSION['login'] == "yes")
{
 // show expanded menu
}
else
{
 // show normal menu
}

What I am seeing now after logging out is the expanded menu. It seems that the menu is being included faster than the session can be destroyed, thus creating an impression that the user is still logged in. Is there a way to avoid such a situation?

Upvotes: 0

Views: 58

Answers (3)

Paul Dixon
Paul Dixon

Reputation: 300825

session_destroy doesn't unset the $_SESSION array, so the rest of the page after session_destroy will still see it. You could simply try this

session_destroy(); 
unset($_SESSION);

Upvotes: 1

alex
alex

Reputation: 490173

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.

Source.

Upvotes: 1

RaYell
RaYell

Reputation: 70414

To completely clear all session data you have to use something similar to

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

This is explained in PHP manual:

session_destroy() destroys all of the data associated with the current session. 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.

Upvotes: 0

Related Questions