Authentication · Lesson 5 of 7
Logout
Invalidate server-side session state and expire the session cookie.
Lesson
Logout should clear the authenticated session on the server and expire the browser's session cookie using the same path and attributes. A redirect alone does not log a user out. Protect logout against CSRF when it changes state, and avoid leaving long-lived authentication tokens active.
The example clears session data and removes the cookie before destroying the session.
Further guidance
Use PHP password hashing APIs, regenerate a session identifier after authentication, and clear session state during logout. Authentication identifies the user; authorization checks whether that user may perform this action on this record. Rate-limit sensitive endpoints and keep failure messages generic.
Practice task: Create a fresh example for Logout. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
Logout
PHP
session_start();
$_SESSION = [];
session_destroy();
if (ini_get('session.use_cookies')) {
$cookie = session_get_cookie_params();
setcookie(session_name(), '', [
'expires' => time() - 42000,
'path' => $cookie['path'],
'domain' => $cookie['domain'],
'secure' => $cookie['secure'],
'httponly' => $cookie['httponly'],
'samesite' => $cookie['samesite'] ?? 'Lax',
]);
}
Expected output
The current server-side session is destroyed
Key points
- Invalidate server-side session state and expire the session cookie.
- Store password hashes, not plaintext passwords.
- Check authorization on every protected operation.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.