top of page

Implement a session timeout mechanism in PHP

 Implement a session timeout mechanism in PHP. It involves creating three files:

  1. login.php - A page for user login.

  2. protected_page.php - A protected page accessible only to logged-in users.

  3. logout.php - A page to log out the user.


1. login.php (Implement a session timeout)


This file provides a simple form for the user to log in.



<?php

session_start();

// Handle form submission

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // In a real-world scenario, you'd validate user credentials here

    $username = $_POST['username'];

    $password = $_POST['password'];

    // Let's assume login is successful

    if ($username === "user" && $password === "password") {

        $_SESSION['user_id'] = 1; // Set a user identifier

        $_SESSION['last_activity'] = time(); // Record the time of login

        header("Location: protected_page.php"); // Redirect to protected page

        exit();

    } else {

        $error_message = "Invalid username or password!";

    }

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Login Page</title>

</head>

<body>

    <h1>Login</h1>

    <?php if (!empty($error_message)): ?>

        <p style="color:red;"><?php echo $error_message; ?></p>

    <?php endif; ?>

    <form method="POST" action="">

        <label for="username">Username:</label>

        <input type="text" name="username" id="username" required><br><br>

        <label for="password">Password:</label>

        <input type="password" name="password" id="password" required><br><br>

        <button type="submit">Login</button>

    </form>

</body>

</html>

2. protected_page.php (Implement a session timeout)


This is the protected page that is only accessible if the user is logged in



<?php

session_start();

// Define session timeout duration (e.g., 10 minutes)

$timeout_duration = 600;

// Check if the user is logged in

if (!isset($_SESSION['user_id'])) {

    header("Location: login.php");

    exit();

}

// Check for session timeout

if (isset($_SESSION['last_activity'])) {

    // Calculate the time elapsed since the last activity

    $elapsed_time = time() - $_SESSION['last_activity'];

    // If the elapsed time is greater than the timeout duration, destroy the session

    if ($elapsed_time > $timeout_duration) {

        session_unset(); // Unset all session variables

        session_destroy(); // Destroy the session

        header("Location: login.php?timeout=true"); // Redirect to login page with a timeout message

        exit();

    }

}

// Update last activity time

$_SESSION['last_activity'] = time();

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Protected Page</title>

</head>

<body>

    <h1>Welcome to the Protected Page!</h1>

    <p>You are currently logged in. This page will timeout after 10 minutes of inactivity.</p>

    <a href="logout.php">Logout</a>

</body>

</html>

3. logout.php


This page logs the user out by destroying the session.



<?php

session_start();

session_unset(); // Unset all session variables

session_destroy(); // Destroy the session

header("Location: login.php?logout=true"); // Redirect to login page with a logout message

exit();

?>

Optional: Modifying login.php to Show Timeout/Logout Messages


You can modify login.php to show a message if the session has timed out or if the user has logged out.

Add this to login.php:



<?php

// Display timeout or logout messages

if (isset($_GET['timeout']) && $_GET['timeout'] == 'true') {

    echo "<p style='color: red;'>Session timed out. Please log in again.</p>";

}

if (isset($_GET['logout']) && $_GET['logout'] == 'true') {

    echo "<p style='color: green;'>You have successfully logged out.</p>";

}

?>

Summary of Files


  1. login.php: Handles the user login. If the credentials are valid, a session is started.

  2. protected_page.php: A protected page accessible only if the user is logged in. Implements session timeout logic.

  3. logout.php: Logs out the user by destroying the session and redirects to the login page.

The session timeout feature ensures that users are automatically logged out after a period of inactivity, enhancing both security and user experience.

Related Posts

See All

Create PHP MySQL Login System

Implementing User Authentication Mechanism User authentication is very common in modern web application. It is a security mechanism that...

Comments


Commenting has been turned off.
bottom of page