Prevent Multiple Login With Same User in PHP


In this tutorial we will see preventing multiple logins with the same user in PHP enhances security by ensuring that a user can only be logged in from one session at a time. This is achieved by storing a unique session ID in the database when a user logs in and verifying it on each page load. If a different session ID is detected, the user is logged out automatically. This method helps prevent unauthorized access and account sharing.

Files and Directory

Prevent-Multiple-Login/
  ├── config.php
  ├── dashboard.php
  ├── index.php
  ├── logout.php

Creating the Database Table

Execute the following SQL query to create a table named 'tbl_users' inside your MySQL database named 'db_sample'.

 
CREATE TABLE  tbl_users (
  id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(150) NOT NULL UNIQUE,
  password varchar(50) NOT NULL,
  session_id varchar(50) DEFAULT NULL,
  PRIMARY KEY (id)
);

Create PHP Files

config.php

This line connects to a MySQL database named db_sample using mysqli_connect(). It uses localhost as the host, with root as the username and no password.

config.php
<?php 
  #Connect Database
  $con = mysqli_connect("localhost", "root", "", "db_sample");
?>

Create PHP Files

index.php

  • This PHP login script verifies user credentials against a database, prevents multiple logins using session tracking, and redirects authenticated users to the dashboard.
  • The interface is styled with Bootstrap for a modern and responsive design.
index.php
<?php
    session_start();
    include 'config.php';

    $error = '';

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $username = mysqli_real_escape_string($con, $_POST['username']);
        $password = $_POST['password']; 
        
        $sql = "select id, username, password from tbl_users where username = '{$username}' and password = '{$password}' ";
        $result = mysqli_query($con, $sql);

        if ($result && mysqli_num_rows($result) > 0) {
            $user = mysqli_fetch_assoc($result);
            
            if($user["password"] == $password){   

                $session_id = session_id(); 
                $sql = "update tbl_users set session_id = '{$session_id}' where id = {$user["id"]}";
                $con->query($sql);
                
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['session_token'] = session_id();

                header("Location: dashboard.php");
                
            } else {
                $error = "Invalid credentials";
            }
        } else {
            $error = "Invalid credentials";
        }
    }    
?>

<html>
    <head>
        <title>Login</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    </head>
    <body class="bg-light">
        <div class="container d-flex justify-content-center align-items-center min-vh-100">
            <div class="card shadow-sm" style="width: 100%; max-width: 450px;">
                <div class="card-body p-4">
                    <div class="text-center mb-4">
                        <i class="fas fa-user-circle fa-3x text-primary"></i>
                        <h3 class="mt-3">Login Here</h3>
                    </div>

                    <?php if (!empty($error)): ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <?php echo $error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <form method="post" action="">
                        <div class="mb-3">
                            <label class="form-label">Username</label>
                            <input type="text" class="form-control" name="username" required placeholder="Enter username">
                        </div>

                        <div class="mb-4">
                            <label class="form-label">Password</label>
                            <input type="password" class="form-control" name="password" required placeholder="Enter password">
                        </div>

                        <input type="submit" class="btn btn-primary w-100 py-2 mb-3" value="Login">
                    </form>
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    </body>
</html>

dashboard.php

  • This PHP dashboard script ensures only authenticated users can access the page and prevents multiple logins by validating the session ID.
  • It displays a welcome message with the logged-in username and provides a logout option.
dashboard.php
<?php
    session_start();
    include "config.php";

    if (!isset($_SESSION["user_id"])) {
        header("Location: index.php");
        exit();
    }

    $session_id = session_id();

    // Fetch user details
    $sql = "select * from tbl_users where id = '{$_SESSION["user_id"]}'";
    $result = mysqli_query($con, $sql);
    $row = mysqli_fetch_assoc($result);

    if (!$row || $row['session_id'] !== $session_id) {
        session_destroy();
        header("Location: index.php");
        exit();
    }
?>

<html>
    <head>
        <title>Dashboard</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    </head>
    <body class="bg-light">
        <div class="container py-5">
            <div class="row justify-content-center">
                <div class="col-md-8 col-lg-6">
                    <div class="card shadow-sm border-0 mt-5">
                        <div class="card-body p-4 text-center">
                            <div class="mb-4">
                                <i class="fas fa-user-check fa-3x text-success"></i>
                                <h3 class="mt-3">Welcome back</h3>
                            </div>
                            
                            <div class="alert alert-success border-0 bg-light">
                                <p class="mb-0">You are logged in as <strong><?php echo htmlspecialchars($row['username']); ?></strong></p>
                            </div>
                            
                            <div class="d-grid gap-2 mt-4">
                                <a href="logout.php" class="btn btn-outline-danger rounded-pill">Logout</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body> 
</html>

logout.php

  • This PHP logout script clears the user's session from the database, ensuring they cannot stay logged in on multiple devices, and then redirects them to the login page.
  • It also destroys the session to enhance security.
logout.php
<?php
    session_start();
    include 'config.php';

    $user_id = $_SESSION['user_id'];

    if ($user_id) {
        // Clear session from DB
        $sql = "update tbl_users set session_id = NULL where id = '{$user_id}'";
        mysqli_query($con, $sql);
    }
    session_destroy();
    header("Location: index.php");
    exit();
?>

Output

1. Prevent Multiple Logins - Login Page

This page prompts users to enter their credentials. If the same user is already logged in elsewhere, they will be restricted from logging in again.

Prevent multiple login with same user login page in php

2. Prevent Multiple Logins - Dashboard Page

Upon successful login, the user is redirected to the dashboard. If the same account is accessed from another device, the session is invalidated to prevent duplicate logins.

Prevent multiple login with same user dashboard page in php