Using sessions & session variables in a PHP Login Script
Building a registration and login system often triggers that specific moment of confusion where the logic seems solid, but the state management fails. You want to know if a user is authenticated without forcing them to reload the page or redirecting them to a dashboard. The solution lies in understanding how PHP handles session data. Specifically, you need to store a simple flag in a session variable to track login status and then check that flag at the start of every protected script.
When a user registers successfully, your database query likely returns true. At this exact moment, before any HTML is output, you must initialize the session if it hasn't already been started by session_start(). Once initialized, you create a new variable in the session array with a value that indicates success. A common convention is to set a variable named logged_in to true. This action persists the data on the server side, linked to the user's browser via a cookie. Without this step, every time the page reloads or a link is clicked, PHP treats the request as stateless, and your conditional logic will always default to the "not logged in" path.
Consider a simple structure where you have a login.php file handling the form submission and authentication. Inside the script, after verifying the username and password against your database, you execute the session assignment:
session_start();
// ... database validation logic ...
if ($valid_credentials) {
// Store the login status in the session
$_SESSION['logged_in'] = true;
// Optionally store user ID for easier access later
$_SESSION['user_id'] = $user_id;
header('Location: dashboard.php');
exit;
} else {
// Handle invalid credentials
$error = "Invalid credentials";
include 'login_form.php';
}
In this example, the redirection is critical. If you don't redirect after setting the session variable, the script continues executing, potentially outputting login forms again. This creates a security risk where an unauthenticated user could see parts of the protected interface. The exit statement ensures the script stops immediately after the header change.
Once the session is set, you need a way to read it on any subsequent page. You can wrap your main application logic with a simple conditional check at the very top of your dashboard or private area:
session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
header('Location: login.php');
exit;
}
This pattern effectively splits your application into two distinct states. If the session variable exists and holds the truthy value, the code proceeds to render the dashboard content. If it is missing or false, the user is immediately redirected back to the login form. This keeps your templates clean because you don't need to duplicate HTML blocks for logged-in versus logged-out users; instead, you rely on the session state to determine which view logic runs.
One common pitfall involves how long a user stays logged in by default. PHP sessions have a lifetime defined by the session.gc_maxlifetime directive in your php.ini file. If a user logs out or closes their browser and the session is destroyed, they must log in again. While this is standard behavior, you might consider implementing custom logout logic that explicitly sets $_SESSION['logged_in'] = false or calls session_destroy() to ensure the session cookie is cleared from the client's domain.
For developers looking to streamline these repetitive state management tasks without reinventing the wheel, frameworks like Laravel handle sessions automatically with robust security features. You can find more information on implementing secure session handling in their documentation at https://laravelcompany.com.
