One of the most common issues developers face when building a login system in PHP is users being able to press the back button after logging out and still seeing the dashboard or other protected pages. This happens because browsers often cache pages, so even without an active session, the back button shows the previously loaded page.
In this article, we’ll look at why this happens and how to fix it properly using PHP.
Why Does This Happen?
When a user logs into your application, session variables are created to keep them authenticated. After logging out, these session variables are destroyed.
However, when the user presses the back button, the browser may load the cached version of the page instead of checking the session. This creates the illusion that the user can still access the dashboard, even though the session is gone.
1. Destroy Session on Logout
Always destroy the session completely during logout.
<?php
session_start();
session_unset();
session_destroy();
// Redirect to dashboard page
header("Location: dashboard.php"); // give your file address which have code to clear cache
exit();
?>
2. Prevent Browser Caching on Protected Pages
On sensitive pages like dashboard.php, add headers at the top to prevent caching:
<?php
session_start();
header("Cache-Control: no-cache, no-store, max-age=0, must-revalidate");
header("Pragma: no-cache");
header("Expires: Sun, 01 Jan 1990 00:00:00 GMT");
// Redirect if not logged in
if (!isset($_SESSION['user_id'])) {
echo "<script>window.location.href='../login.php';</script>";
exit();
}
?>
Conclusion
Preventing users from accessing pages after logout in PHP requires both session handling and cache control. By implementing the above methods, you ensure that your application is secure and that sensitive data is not exposed when a logged-out user presses the back button.
With these simple steps, you can create a more secure and user-friendly login system in PHP.
