34

Is it enough to

session_start();   //  Must start a session before destroying it

if (isset($_SESSION))
{
    unset($_SESSION);
    session_unset();
    session_destroy();
}

when the user selects Log out from a menu, but does not quit his browser? I want to totally remove all existence of the session and $_SESSION

NikiC
  • 100,734
  • 37
  • 191
  • 225
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
  • 4
    I wouldn't `unset($_SESSION);` before `session_destroy()`, it could be that session_destroy is unable to work properly – Pekka Oct 16 '10 at 09:21

1 Answers1

69

According to the manual, there's more to do:

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.

The manual link has a full working example on how to do that. Stolen from there:

<?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();
?>
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 6
    why not use `session_unset` instead of `$_SESSION = array();`? – alexw Jun 04 '16 at 01:47
  • I tested here and you can use unset($_SESSION) or assigning null to $_SESSION or an empty array like Pekka has done! – Zanoldor Jan 13 '17 at 15:50
  • 1
    @alexw read the docs. `Note: Only use session_unset() for older deprecated code that does not use $_SESSION.` – Keno Apr 29 '18 at 23:14