How to prevent a user to login in multiple devices with same login access in PHP?

How to prevent a user to login in multiple devices with same login access in PHP?

How to prevent a user to login in multiple devices with same login access in PHP?

This is not a common requirement and we can say generally it doesn’t require putting some kind of restriction on Login on the behalf of device or channel (Multiple Browser).

Here we are going to go through step by step process of implementation of code & logic to prevent multiple login from same login access in multiple devices.

If we are working on a project which relates with financial domain or project risk level is high. We use this kind of restrictions/ preventions and security parameters in our process through code.

So, let’s start the step by Step process of implementation.

Step 1: Create Table tbl_user to store login access of user.

Create table tbl_user (
id int(10) NOT NULL auto_increment,
user_id varchar(100),
password varchar(100)
created_date varchar(100),
status int(2), primary key(id));

I am using a very simple table structure for better understanding. You can modify it as per your requirement.

Here are two important fields user_id and password.

Step 2: Create Table tbl_user_token to store dynamic created token value during login of user.

Create table tbl_user_token (
id int(10) NOT NULL auto_increment,
user_id int(10),
token varchar(500),
created_date  varchar(100),
status int(2), primary key(id));

Every time user when login into system through their access one token value will be inserted in this table with status 1.

Step 3: Create HTML Login page i.e. login.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width = device-width, initial-scale = 1.0">
        <meta http-equiv="X-UA-Compatible" content = "ie=edge">
        <title> Login Check </title>
    </head>
    
    <body>
        <form action="/authenticate.php" method="post" enctype="multipart/form-data">
       <div class="form-group">
           <label for="exampleInputEmail1">User ID</label>
           <input type="email" class="form-control" id="exampleInputEmail1" name="userId" aria-describedby="emailHelp" placeholder="Enter User ID">
           <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
       </div>
       <div class="form-group">
           <label for="exampleInputPassword1">Password</label>
           <input type="password" class="form-control" name="password" id="exampleInputPassword1" placeholder="Password">
       </div>
      
       <button type="submit" name="loginSubmit" class="btn btn-primary">Submit</button>
   </form>
    </body>
</html>

Here we are using a simple login page and giving option to user to input ID and Password.

Step 4: Create authenticate.php and Validate Login Credentials

<?php
session_start();
include('config.php'); // for DB Connection
 if($_POST['loginSubmit']){
    $usersql="select * from tbl_user where user_id='$_POST[userId]'";
    $userresult=mysqli_query($con,$usersql);
    $usercount = mysqli_num_rows($userresult);
    if($usercount>0){
        $userrow=mysqli_fetch_array($userresult);
        if($userrow['password']==$_POST['password']){
            $token=uniqid();  // Created Token  
            $date=date('d/m/Y h:i:s);
            $checktoken = "select count(*) from tbl_user_token where user_id='$userrow[id]' and status=1";
            $checktokenresult = mysqli_query($con,$checktoken);
            $checktokenrow = mysqli_fetch_array($checktokenresult);
            if($checktokenrow[0]>0){
                mysqli_query($con,"update tbl_user_token set status=0 where user_id='$userrow[id]'");   // Update all previous active tokens
            }
            mysqli_query($con, "insert into tbl_user_token (user_id,token, created_date, status) values ('$userrow[id]','$token','$date',1)");     // Insert new Token for Current Session
            $_SESSION['token']=$token;   // Store Token in Session Variable
            $_SESSION['userid']=$userrow['id'];
            header('location: successfull.php'); // Successful Login 
        }else{
            echo "<script>Wrong Password</script>";
        }
    }else{
        echo "<script>Wrong User ID!</script>";
    }
}
?>

For understanding purpose, we are using very simple flow of code to authenticate the user credentials and token management for login purpose.

Let’s go to explanation for important points that we have implemented in this flow.

We have checked User Credentials in two steps i.e. Check User ID and Check Password

If both are correct, we are checking previous login tokens active or not. Basically, we are checking that user has any active login access somewhere or not.  If we are getting active login token, we are updating it with status 0 or you may delete it.

On the same time, we are giving a new token to user with current date for particular session.

Note: This step will only update database table tokens. We have to push user on Auto Logout when same user ID accessed in other device.

Step 5: create checkSession.php

<?php
    session_start();
    include('config.php');
    $checktoken = "select * from tbl_user_token where user_id='$_SESSION[userid]' and status=1";
    $checkresult=mysqli_query($con,$checktoken);
    $checkrow=mysqli_fetch_array($checkresult);
    if($checkrow['token']!=$_SESSION['token']){
        header('location: logout.php'); // Redirect User to Logout Page to destroy session
    }
?>

Here in this code, we have checked the current Session variable Token of User with Database Active Token. If it doesn’t match then we are pushing user to Logout or Session destroy.

So, here we have concluded that if a user login into new system or device or any other browser (incognito) then, system will automatically logout old active logins of that particular Login ID.

This is most common use scenario in Offices to prevent unauthorized access.

If somebody has any questions or doubt, please comment below in section.

Write a comment