Logout removes authenticated session state and invalidates the session cookie. Because logout changes server-side state, a POST action with CSRF protection is preferable for production applications.
<form action="mem-logout.php"
method="post">
<input type="hidden"
name="csrf_token"
value="...">
<button type="submit"
class="btn btn-outline-danger">
Logout
</button>
</form>
$_SESSION = [];
if (
ini_get(
'session.use_cookies'
)
) {
$params =
session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
session_destroy();
Validate the CSRF token before clearing the session in a production POST logout handler.
Redirect to login or a public page and confirm that the user has signed out. Do not print old session values or the session ID as part of the logout confirmation.
header(
'Location: mem-login.php?logged_out=1'
);
exit;
session_unset() plus session_destroy() clears server session state, but a complete logout should also clear the session cookie when PHP sessions use cookies.
See PHP sessions.
session_unset();
session_destroy();
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.