Logout & Session Destroy

Logout correctly: session invalidation and cookie cleanup.

On this page

Logout Goal

Logout should invalidate the session and remove any auth-related cookies (including remember-me). In production, be strict: clear session data and destroy the session.

Basic Logout

<?php
session_start();

// clear session array
$_SESSION = [];

// destroy session
session_destroy();

echo "Logged out";

Remove the Session Cookie (Optional but Good)

Also delete the session cookie so the browser stops sending it.

<?php
session_start();

$_SESSION = [];
session_destroy();

$params = session_get_cookie_params();
setcookie(
  session_name(),
  "",
  [
    "expires" => time() - 3600,
    "path" => $params["path"] ?? "/",
    "domain" => $params["domain"] ?? "",
    "secure" => (bool)($params["secure"] ?? true),
    "httponly" => (bool)($params["httponly"] ?? true),
    "samesite" => "Lax",
  ]
);

Remove Remember-me Cookie

If you use remember-me, delete the cookie and delete the corresponding token record in DB (server-side revocation).

<?php
$token = $_COOKIE["remember_token"] ?? "";
if ($token !== "") {
  $tokenHash = hash("sha256", $token);
  $pdo->prepare("DELETE FROM remember_tokens WHERE token_hash = ?")->execute([$tokenHash]);
}

setcookie("remember_token", "", time() - 3600, "/");

Production Tip

Logout is security-critical. Always invalidate server-side state (sessions/tokens), not just UI state. Consider “log out from all devices” by deleting all remember tokens for the user.