PHP MySQL Session management for logged-in users
Session management for logged-in users in PHP MySQL procedural style is essential for maintaining user state across different pages in a web application. After a user logs in, you can use PHP sessions to store information (e.g., user ID, username) and keep them logged in as they navigate through the site.
Steps for Managing Sessions for Logged-in Users:
- Start a session on login.
- Store user data in session variables.
- Use session variables to maintain user state across pages.
- Restrict access to certain pages if the user is not logged in.
- Implement logout functionality to destroy the session.
Example: Session Management for Logged-in Users
Step 1: Starting a Session After Login
In the login script (login.php
), you start a session after verifying the user's credentials. You can store user information (such as user_id
and username
) in session variables.
<?php
session_start(); // Step 1: Start a session at the beginning of the script
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Assume user credentials have been verified
$email = $_POST['email'];
$password = $_POST['password'];
// Connect to the database
$conn = mysqli_connect("localhost", "root", "", "test_db");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Query the user from the database
$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
$user = mysqli_fetch_assoc($result);
// Verify the password
if (password_verify($password, $user['password'])) {
// Step 2: Store user information in session variables
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['loggedin'] = true; // Optional flag to track login state
// Redirect to dashboard or protected page
header("Location: dashboard.php");
exit();
} else {
echo "Incorrect password.";
}
} else {
echo "No user found with that email.";
}
mysqli_close($conn);
}
?>
Explanation:
session_start()
: Always include this at the beginning of any script where you want to access session variables.- Storing session variables: Once the user is authenticated, you store their
user_id
,username
, and other details in the$_SESSION
superglobal array. This keeps the user’s data available throughout their session.
Step 2: Using Session Data in Other Pages
On any other page (e.g., a dashboard or profile page), you can check if the user is logged in by inspecting the session variables.
<?php
session_start(); // Start session at the beginning of every page where session is required
// Step 3: Check if the user is logged in
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
echo "Welcome, " . $_SESSION['username'] . "!";
} else {
// If not logged in, redirect to login page
header("Location: login.php");
exit();
}
?>
Explanation:
- Check if the user is logged in: The presence of the session variable
$_SESSION['loggedin']
is used to determine if the user is logged in. If not, the user is redirected to the login page.
Step 3: Restrict Access to Protected Pages
You can prevent unauthorized access to certain pages by checking if the user is logged in before displaying content. If not logged in, they are redirected to the login page.
<?php
session_start(); // Always start session to access session data
// Step 4: Redirect if not logged in
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header("Location: login.php");
exit();
}
// Protected page content
echo "This is a protected page for logged-in users only. Welcome, " . $_SESSION['username'] . "!";
?>
Step 4: Implementing Logout
To log a user out, destroy the session and redirect them to the login page.
<?php
session_start(); // Start session to access session data
// Step 5: Destroy the session to log the user out
session_unset(); // Unset all session variables
session_destroy(); // Destroy the session
// Redirect to login page
header("Location: login.php");
exit();
Explanation:
session_unset()
: This function removes all session variables.session_destroy()
: This function destroys the session, effectively logging out the user.- After destroying the session, the user is redirected to the login page.
Best Practices for Session Management:
Use HTTPS: Always use HTTPS to encrypt session data during transmission to prevent session hijacking.
Regenerate Session ID: Use
session_regenerate_id()
after successful login to prevent session fixation attacks.session_start(); session_regenerate_id(true); // Regenerate session ID to prevent fixation attacks
Set Cookie Parameters: Use secure cookie parameters to prevent cookie theft.
session_set_cookie_params([ 'lifetime' => 0, // Session cookies will expire when the browser is closed 'path' => '/', // Cookie is available across the entire site 'domain' => '', // Cookie is available only within the current domain 'secure' => true, // Only send cookie over HTTPS 'httponly' => true, // Only accessible through the HTTP protocol (not by JavaScript) 'samesite' => 'Strict' // Prevents cross-site request forgery (CSRF) attacks ]); session_start();
Session Timeout: Implement a session timeout feature to automatically log users out after a certain period of inactivity.
session_start(); // Set session timeout period in seconds $timeout_duration = 1800; // 30 minutes // Check for last activity timestamp if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) { // If the session has timed out, destroy the session session_unset(); session_destroy(); header("Location: login.php"); // Redirect to login page exit(); } // Update the last activity time $_SESSION['LAST_ACTIVITY'] = time();
Use Session IDs Correctly: Always verify that the session ID is not exposed in URLs, and avoid using it in GET parameters.
Conclusion:
Session management in PHP using MySQL (procedural style) helps maintain user state after login. The key steps include:
- Starting a session after login and storing relevant user information in session variables.
- Accessing session data on other pages to maintain the user's logged-in status.
- Protecting pages by checking the session status.
- Implementing a logout function to destroy the session.