User Logout
Overview
Section titled โOverviewโLogout is the process of terminating a userโs authenticated session and clearing their state. After logging out, the user can no longer access protected pages until they log in again.
The key steps are:
- User clicks the โLogoutโ button.
- Server clears all session data.
- Server issues a new session ID.
- User is redirected to the login page.
- The previous session cannot be reused.
Ending the Session
Section titled โEnding the SessionโA proper logout must do more than clear a single variable. To fully end the logged-in session:
- Unset all session variables to clear the
$_SESSIONarray. - Remove the old session file from the server, so the old session ID cannot be reused.
In your application, the logout action calls SessionManager::clear() to unset all session variables, then SessionManager::regenerate() to issue a new session ID and delete the old session file. The browser keeps a session cookie, but it now points to a new, empty session.
The application does not call SessionManager::destroy() here. After session_destroy(), PHP no longer saves anything written to $_SESSION during the request, so the โYou have been logged outโ flash message would be lost. Clearing and regenerating gives the same protection while keeping a fresh session for that message.
Logout Flow
Section titled โLogout Flowโโโโโโโโโโโโโโโโโโโโโ User clicks โโ Logout button โโโโโโโโโโโฌโโโโโโโโโ โ โผโโโโโโโโโโโโโโโโโโโโ POST /logout โโโโโโโโโโโฌโโโโโโโโโ โ โผโโโโโโโโโโโโโโโโโโโโ Clear session โโ - Unset vars โโ - New ID โโโโโโโโโโโฌโโโโโโโโโ โ โผโโโโโโโโโโโโโโโโโโโโ Show success โโ flash message โโโโโโโโโโโฌโโโโโโโโโ โ โผโโโโโโโโโโโโโโโโโโโโ Redirect to โโ /login โโโโโโโโโโโโโโโโโโโโSecurity Note
Section titled โSecurity NoteโYour application uses a POST request for logout, because logging out changes state. A GET-based logout is vulnerable to CSRF attacks where an attacker could log a user out by tricking their browser into visiting the logout URL (for example, through an image tag like <img src="/logout">).
The session cookie from Lab 4 also uses SameSite=Strict, so the browser does not send it with requests that start on another site. This is extra protection, not a replacement: production applications should also include a CSRF token in every POST form.