Skip to content

User Logout

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:

  1. User clicks the โ€œLogoutโ€ button.
  2. Server clears all session data.
  3. Server issues a new session ID.
  4. User is redirected to the login page.
  5. The previous session cannot be reused.

A proper logout must do more than clear a single variable. To fully end the logged-in session:

  1. Unset all session variables to clear the $_SESSION array.
  2. 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.


โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ User clicks โ”‚
โ”‚ Logout button โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ”‚
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ POST /logout โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ”‚
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Clear session โ”‚
โ”‚ - Unset vars โ”‚
โ”‚ - New ID โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ”‚
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Show success โ”‚
โ”‚ flash message โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ”‚
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Redirect to โ”‚
โ”‚ /login โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

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.