Prevent multiple login of same account with PHP

To prevent the same user login on multiple systems or web browsers you need to generate a token on each successful login attempt and store in the database table user wise.

Also, require using a SESSION variable to store the current token and check with the stored token in the database table.

If it not matched then log out the user.

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 user_token table in the tutorial example.

CREATE TABLE `user_token` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `token` varchar(80) NOT NULL,
  `timemodified` timestamp NOT NULL,
  PRIMARY KEY (`id`)
) 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

When form got submitted then check the user in the MySQL database table by its entered username and password.

If it is available then initialize a $_SESSION['username'] and generate a token value to initialize $_SESSION['token'] varaible

Check user record already exist or not in the user_token table if it exists then update the token 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 to check the user token on required pages.

If the user $_SESSION['token'] not match with the database table token 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 that 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 find this tutorial helpful then share with your friends or on social media.

Related Post

Spread the love

One Comment

  1. rik said:

    Nice post and very usefull!
    rik

    September 15, 2017
    Reply

Leave a Reply

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