Creating a Logout Page
Logout should remove server-side session data, expire the session cookie and return the user to a safe public page.
Logout script
Create logout.php:
<?php
session_start();
$_SESSION = [];
if (ini_get("session.use_cookies")) {
$parameters = session_get_cookie_params();
setcookie(
session_name(),
"",
time() - 42000,
$parameters["path"],
$parameters["domain"],
$parameters["secure"],
$parameters["httponly"]
);
}
session_destroy();
header("Location: login.php");
exit;
Clearing $_SESSION removes values in the current request. Expiring the cookie removes the browser’s session identifier. session_destroy() removes the stored session.
Logout control
For a basic local classroom project:
<a href="logout.php">Log out</a>
For a stronger design, use a POST form and a CSRF token so another website cannot trigger logout unexpectedly.
Test
- Log in and open a protected page.
- Log out.
- use the Back button and refresh.
- enter the protected URL directly.
- confirm the application requires login again.
Check
- Session array is cleared.
- Session cookie is expired when cookies are used.
- Stored session is destroyed.
- Redirect is followed by
exit. - Protected content is unavailable after logout.