kdubs
kdubs

Reputation: 1722

how to logout from a php session - session_destroy doesn't seem to be enough

I'm trying to learn PHP and using sessions. I seen examples about using session_destroy on logout, but I see this in the php documentation:

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.

so what does one need to do upon logout ?

Upvotes: 1

Views: 10408

Answers (6)

vinod kumar
vinod kumar

Reputation: 31

Only use session_unset() for older deprecated code that does not use $_SESSION.

session_start();

session_unset($_SESSION['email-user']); session_destroy();`

Upvotes: 0

codename_subho
codename_subho

Reputation: 476

if you are using session id. then you can do this

session_start();
unset($_SESSION['id']);
session_destroy();

for cookies you can set the cookie time to some past date.

Upvotes: 0

Donny van V
Donny van V

Reputation: 961

At the first: use the unset() function. So if you have a $_SESSION['user_id'], and you wanne destroy it: unset($_SESSION['user_id'])

You can also use the unset() for cookies or other vars

Second: can we have some code?

Upvotes: 0

Sam
Sam

Reputation: 20486

I've never actually deleted the session ID from the session. I usually just unset the necessary variables from the session (so if, for instance, you set a logged in user as $_SESSION['user'] = $userModel; then I just unset($_SESSION['user']);). To remove the cookie from the user's browser (like the documentation says) do this:

setcookie(session_id(), "", time() - 3600);

Read Example #1 from the session_destroy() documentation for more info.

Upvotes: 0

hanzi
hanzi

Reputation: 2987

There's, like, an example answering your question just below the paragraph you just quoted: http://php.net/manual/en/function.session-destroy.php

Example #1 Destroying a session with $_SESSION

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

Upvotes: 5

Jeroen Ketelaar
Jeroen Ketelaar

Reputation: 102

In my opinion only this is nesessary

session_start();
unset($_SESSION["nome"]);  // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**

Upvotes: 0

Related Questions