Prevent multiple login of same account with PHP

Sometimes required to restrict the user to only log in on a single system or a browser at a time.

To prevent the user from login on multiple systems or web browsers you need to generate a token on each successful login attempt.

Need to check the token on each page. If the token does not match then destroy the SESSION and log out the user.

In this tutorial, I show how you can prevent multiple logins of the same user with PHP.

Prevent multiple login of same account with PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. CSS
  5. PHP
  6. Conclusion

 


1. Table structure

I am using users and user_token table in the tutorial example.

users table –

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(60) NOT NULL,
  `fullname` varchar(70) NOT NULL,
  `password` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

user_token table –

CREATE TABLE `user_token` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `token` varchar(80) NOT NULL,
  `timemodified` timestamp NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php for database connection.

Completed Code

<?php
session_start();
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Create a login form with two input elements and a submit button.

Completed Code

<div class="container">
 <form method="post" action="">
  <div id="div_login">
   <h1>Login</h1>
   <div>
    <input type="text" class="textbox" id="txt_uname" name="txt_uname" placeholder="Username" />
   </div>
   <div>
    <input type="password" class="textbox" id="txt_uname" name="txt_pwd" placeholder="Password"/>
   </div>
   <div>
    <input type="submit" value="Submit" name="but_submit" id="but_submit" />
   </div>
  </div>
 </form>
</div>

4. CSS

/* Container */
.container{
 width:40%;
 margin:0 auto;
}

/* Login */
#div_login{
 border: 1px solid gray;
 border-radius: 3px;
 width: 470px;
 height: 270px;
 box-shadow: 0px 2px 2px 0px gray;
 margin: 0 auto;
}

#div_login h1{
 margin-top: 0px;
 font-weight: normal;
 padding: 10px;
 background-color: cornflowerblue;
 color: white;
 font-family: sans-serif;
}

#div_login div{
 clear: both;
 margin-top: 10px;
 padding: 5px;
}

#div_login .textbox{
 width: 96%;
 padding: 7px;
}

#div_login input[type=submit]{
 padding: 7px;
 width: 100px;
 background-color: lightseagreen;
 border: 0px;
 color: white;
}

/* media */
@media screen and (max-width:720px){
 .container{
  width: 100%;
 }
 #div_login{
  width: 99%;
 }
}

5. PHP

Check login & generate token

On <form> submit match username and password in the users table.

If record is available then initialize a $_SESSION['username'] and generate a token value to initialize $_SESSION['token'] variable.

Check user record already exist or not in the user_token table if it exists then update the token field value otherwise insert a new record.

Completed Code

<?php
include "config.php";

if(isset($_POST['but_submit'])){

 $uname = mysqli_real_escape_string($con,$_POST['txt_uname']);
 $password = mysqli_real_escape_string($con,$_POST['txt_pwd']);

 if ($uname != "" && $password != ""){

  $sql_query = "select count(*) as cntUser from users where username='".$uname."' and password='".$password."'";
  $result = mysqli_query($con,$sql_query);
  $row = mysqli_fetch_array($result);

  $count = $row['cntUser'];

  if($count > 0){
   $token = getToken(10);
   $_SESSION['username'] = $uname;
   $_SESSION['token'] = $token;

   // Update user token 
   $result_token = mysqli_query($con, "select count(*) as allcount from user_token");
   $row_token = mysqli_fetch_assoc($result_token);
   if($row_token['allcount'] > 0){
    mysqli_query($con,"update user_token set token='".$token."' where username='".$uname."'");
   }else{
    mysqli_query($con,"insert into user_token(username,token) values('".$uname."','".$token."')");
   }
   header('Location: home.php');
  }else{
   echo "Invalid username and password";
  }

 }

}

// Generate token
function getToken($length){
 $token = "";
 $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
 $codeAlphabet.= "0123456789";
 $max = strlen($codeAlphabet); // edited

 for ($i=0; $i < $length; $i++) {
  $token .= $codeAlphabet[random_int(0, $max-1)];
 }

 return $token;
}

Check token

Create a new check_token.php file to check the user token on required pages.

If the user $_SESSION['token']does not match with the value stored in user_token table means the user is logged in on some other browser or system.

Destroy the SESSION and redirect to the index page.

Completed Code

<?php

if (isset($_SESSION['username'])) {
  $result = mysqli_query($con, "SELECT token FROM user_token where username='".$_SESSION['username']."'");
 
  if (mysqli_num_rows($result) > 0) {
 
   $row = mysqli_fetch_array($result); 
   $token = $row['token']; 

   if($_SESSION['token'] != $token){
    session_destroy();
    header('Location: index.php');
   }
  }
}

Create a new home.php file. This file will show after login. Include above created check_token.php file after config.php.

Completed Code

<?php
include "config.php";
include "check_token.php";  // Check user token

// Check user login or not
if(!isset($_SESSION['username'])){
 header('Location: index.php');
}

// logout
if(isset($_POST['but_logout'])){
 session_destroy();
 header('Location: index.php');
}
?>
<!doctype html>
<html>
 <head></head>
 <body>
  <h1>Homepage</h1>
  <form method='post' action="">
   <input type="submit" value="Logout" name="but_logout">
  </form>
 </body>
</html>

6. Conclusion

Using above PHP script you can prevent the multiple logins of the user and automatically log out from other places when it gets logged in.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 2
  •  
  •  
  •  
  •  
  •  

10 Comments

  1. rik said:

    Nice post and very usefull!
    rik

    September 15, 2017
    Reply
  2. Waqas Saeed said:

    Thank you for this, I modified it a bit to work with my CakePHP app but it works great. Now to decide whether it’s

    October 8, 2018
    Reply
  3. syahira said:

    im sorry. im new to this PHP.

    may i know. do i have to create users table in the tutorial database? im copying exactly your codes but it shows invalid username.

    November 16, 2018
    Reply
  4. Kal An Zans said:

    Thank you, master! Sensational! Grettings from Brazil!

    November 20, 2018
    Reply
  5. Snigdharani Sahoo said:

    Sir actually i’ve created a my_database inside that one user table may i know where i will create a user_token table?

    December 11, 2018
    Reply
    • Yogesh Singh said:

      Hi Snigdharani,
      Create the user_token table on the same database.

      December 11, 2018
      Reply
  6. Snigdharani Sahoo said:

    this demo project is not working

    December 11, 2018
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *