PHP: How to properly destroy session, delete session data and unset session variables

2.4k views Asked by At

I am new to PHP sessions and am looking for some help with the following:

I start a session on a page as follows which works as intended so far:

session_start();
// ...
$_SESSION["User"]["login"] = "loggedIn";
$_SESSION["User"]["username"] = $email;

Now if a the user wants to log out I also want to destroy this session (incl. deleting its data and unsetting its variables etc.). When searching for guidelines on this I came across the following on the PHP Manual but I am not sure how to apply this and I don't understand what the lines in the ini part really do.

Can someone help me with this and maybe also provide some short explanations on this ?

My current code to destroy the session:

session_start();
// ...
$_SESSION = array();
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $_SESSION["User"]["login"] = "",
        $_SESSION["User"]["username"] = ""
    );
}
session_destroy();

Many thanks in advance.

2

There are 2 answers

2
Abhinav On BEST ANSWER

This is what PHP manual says

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

Checkout the PHP Manual

You can use unset($_SESSION);

OR

$_SESSION = array();

This will also empty the Session datas

0
BaBL86 On

You don't need to destroy $_SESSION, PHP Garbage Collector do this automatically.

Just set $_SESSION["User"]["login"] = false and everywhere you need to check user login, check

if ($_SESSION["User"]["login"]) {
    // do something
} else {
    echo "You don't have access";
}