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.
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
Surely you would just have $SESSION_DESTROY(); on its own, without $SESSION_START(); within the logout page ?
You have to use Page_init() event to check for users session variable. If you check users session variable at page load then it will show you as a active session. There is only way in which you can check users session at Page_init() event as follows..
protected void Page_init(object sender, EventArgs e)
{
if (Session["User"] == null)
{
Response.Redirect("home.aspx");
}
}
you can use this event on all the pages, so if you destroy the session using session_destroy(); method then you are redirected to login page.
Thank You