0

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.

1
  • unset($_SESSION) did try this one Commented Jun 26, 2015 at 4:57

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot - this is great ! In my case it can happen that one user is registered with two different email addresses for different purposes so I want to allow them to be able to log out from one email and then log in with another one without the need to close the browser. I would like to go with this approach so considering the above would I just use unset($_SESSION); for the variables and then session_destroy(); for the actual session ? What I want to make sure is that both the session and its variables are destroyed / deleted.
yes..definitely, you just have to use unset function and then session_destroy(). That will do the job
1

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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.