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" required />
   </div>
   <div>
    <input type="password" class="textbox" id="txt_pwd" name="txt_pwd" placeholder="Password" required />
   </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 a token

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

If a 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.

Redirect to home.php file.

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 where username='".$uname."' ");
    $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 the required pages.

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

Destroy the SESSION and redirect it to the index.php file.

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');
    }
  }
}

Homepage

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

If $_SESSION['username'] is not set then redirect to index.php file.

Created an anchor element for logout.

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');
}

?>
<!doctype html>
<html>
 <head></head>
 <body>
    <h1>Homepage</h1>
    <br>
    <a href="logout.php">Logout</a>
 </body>
</html>

Logout

Create a logout.php file for deleting SESSION and user token.

Check if $_SESSION['username'] is set or not. If set then delete a record from the user_token table by username and destroy the SESSION.

Redirect to index.php file.

Completed Code

<?php

include "config.php";

if(isset($_SESSION['username'])){
   // Delete token 
   $uname = mysqli_real_escape_string($con,$_SESSION['username']);
   
   mysqli_query($con, "delete from user_token where username = '".$uname."'");
   
   // Destroy session
   session_destroy();
   header('Location: index.php');
}else{
   header('Location: index.php');
}

6. Conclusion

Using the 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.