Destroy an entire session
suggest changeIf 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();
/*
Clear $_SESSION before destroying the stored session.
session_destroy() removes the stored session, but it leaves the
current request's $_SESSION array in place until you clear it.
*/
$_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 from $_SESSION = array();. Assigning an empty array removes the values in $_SESSION but does not delete the stored session. session_destroy() deletes the stored session and does not, by itself, empty $_SESSION for the rest of this request.
On PHP 7.3 and later, session_get_cookie_params() also includes samesite. Send that attribute on the expiry cookie as well, or the browser may keep the original cookie.
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents