Destroy an entire session

suggest change

If you’ve got a session which you wish to destroy, you can do this with session_destroy()

/*
    Let us assume that our session looks like this:
    Array([firstname] => Jon, [id] => 123)

    We first need to start our session:
*/
session_start();

/*
    We can now remove all the values from the `SESSION` superglobal:
    If you omitted this step all of the global variables stored in the 
    superglobal would still exist even though the session had been destroyed.
*/
$_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 we can destroy the session:
session_destroy();

Using session_destroy() is different to using something like $_SESSION = array(); which will remove all of the values stored in the SESSION superglobal but it will not destroy the actual stored version of the session.


Note: We use $_SESSION = array(); instead of session_unset() because the manual stipulates:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Sessions:
* Destroy an entire session

Table Of Contents
2 Arrays
4 Types
9 Sessions
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR