How to limit login attempt Using PHP and MySQL | E-CODEC



In this tutorial, we will learn, How to limit login attempts Using PHP and MySQL

File Structure and database tables used in this tutorial

Two MySQL Tables used

  • attempt_count (This table stores user login IP address and login attempt time )
  • user_login (user_login table stores the user login details i.e username and password)

PHP FIles used in this tutorials

  • config.php (Database connection file)
  • index.php (user for login and checking the user login attempted)
  • dashboard.php (After successful login user will redirect to this page)
  • logout.php (This file for user logout/ session destroy)


attempt_count MySQL table structure

 CREATE TABLE `attempt_count` (  
  `id` int(11) NOT NULL,  
  `ip_address` varchar(30) NOT NULL,  
  `time_count` bigint(20) NOT NULL  
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;  


user_login MySQL table structure

 CREATE TABLE `user_login` (  
  `id` int(11) NOT NULL,  
  `username` varchar(50) NOT NULL,  
  `password` varchar(50) NOT NULL  
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;  


db_config.php : This file is used for the database connection.

 $conn=mysqli_connect("localhost","root","","tutorials");  


index.php  :  This is the main file used for login and checking the login attempt. First, we will create an HTML form with two fields i.e username and password.

 <form action="" autocomplete="off" method="post">  
               <div class="form-group">  
                 <input type="text" class="form-control" name="username" placeholder="Username">  
               </div>  
               <div class="form-group">  
                 <input type="password" class="form-control" name="password" placeholder="Password">  
               </div>  
               <button type="submit" id="sendlogin" class="btn btn-primary" name="submit">login</button><br><br>  
               <div class="error"><?php echo $msg ?></div>  
             </form>  


Now create a function for IP address

 function getUserIpAddr(){  
   if(!empty($_SERVER['HTTP_CLIENT_IP'])){  
     $ip = $_SERVER['HTTP_CLIENT_IP'];  
   }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){  
     $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
   }else{  
     $ip = $_SERVER['REMOTE_ADDR'];  
   }  
   return $ip;  
 }  

We will store the IP address in a variable and also create a variable for time.

 $ip_address=getUserIpAddr();  
 $time=time()-30; //30 sec  

After this, we will get the login attempt count on the basis of IP address and Try time.

 $check_attmp=mysqli_fetch_assoc(mysqli_query($conn,"select count(*) as total_count from attempt_count where time_count>$time and ip_address='$ip_address'"));  
   //print_r($check_attmp);  
   $total_count=$check_attmp['total_count'];  


If login attempt count equal to 3 (you can change the login attempt according to your need), it will show error message “To many failed login attempts. Please login after 30 sec”.


If login attempt counts not equal to 3 then it will check the login credentials provided by the user then matches with the database record. If the record match, the user will redirect to dashboard.php otherwise the program will check for the remaining login attempt. If a remaining login attempt is 0 it will show error message  “To many failed login attempts. Please login after 30 sec” else it will show “Please enter valid login details.<br/>$time_remain attempts remaining”.

 $msg="";  
 if (isset($_POST['submit'])) {  
   //echo "<pre>";  
   //print_r($_POST);  
   $ip_address=getUserIpAddr();  
   $time=time()-30; //30 sec  
   $check_attmp=mysqli_fetch_assoc(mysqli_query($conn,"select count(*) as total_count from attempt_count where time_count>$time and ip_address='$ip_address'"));  
   //print_r($check_attmp);  
   $total_count=$check_attmp['total_count'];  
   if ($total_count==3) {  
     $msg="Your account blocked. Please try afetr 30 sec";  
   }else{  
     $username=mysqli_real_escape_string($conn,$_POST['username']);  
     $password=mysqli_real_escape_string($conn,$_POST['password']);  
     $sql="select * from user_login where username='$username' and password='$password'";  
     $user_row=mysqli_query($conn,$sql);  
     if (mysqli_num_rows($user_row)>0) {  
       $res=mysqli_fetch_assoc($user_row);  
       $_SESSION['USER_ID']=$res['id'];  
       //Delete data after successfully user login  
       mysqli_query($conn,"delete from attempt_count where ip_address='$ip_address'");  
       header("location:dashboard.php");  
     }else{  
       $total_count++;   
       $time_remain=3-$total_count;  
       $time=time();  
       if ($time_remain==0) {  
         $msg="Your account blocked. Please try afetr 30 sec";  
       }else{  
         $msg="Please enter valid login details. ".$time_remain. " attempts remains";  
       }  
       //Data insert into attempt_count table  
       mysqli_query($conn,"INSERT INTO `attempt_count`(`ip_address`, `time_count`) VALUES ('$ip_address','$time')");  
       //Error Message display after enter wrong details  
       //$msg="Please enter valid login details.";  
     }  
   }  
 }  


Here is the full code that we have written for index.php page

 <?php   
 //Database connectivity  
 //tutorials database name  
 session_start();  
 $conn=mysqli_connect("localhost","root","","tutorials");  
 $msg="";  
 if (isset($_POST['submit'])) {  
   //echo "<pre>";  
   //print_r($_POST);  
   $ip_address=getUserIpAddr();  
   $time=time()-30; //30 sec  
   $check_attmp=mysqli_fetch_assoc(mysqli_query($conn,"select count(*) as total_count from attempt_count where time_count>$time and ip_address='$ip_address'"));  
   //print_r($check_attmp);  
   $total_count=$check_attmp['total_count'];  
   if ($total_count==3) {  
     $msg="Your account blocked. Please try afetr 30 sec";  
   }else{  
     $username=mysqli_real_escape_string($conn,$_POST['username']);  
     $password=mysqli_real_escape_string($conn,$_POST['password']);  
     $sql="select * from user_login where username='$username' and password='$password'";  
     $user_row=mysqli_query($conn,$sql);  
     if (mysqli_num_rows($user_row)>0) {  
       $res=mysqli_fetch_assoc($user_row);  
       $_SESSION['USER_ID']=$res['id'];  
       //Delete data after successfully user login  
       mysqli_query($conn,"delete from attempt_count where ip_address='$ip_address'");  
       header("location:dashboard.php");  
     }else{  
       $total_count++;   
       $time_remain=3-$total_count;  
       $time=time();  
       if ($time_remain==0) {  
         $msg="Your account blocked. Please try afetr 30 sec";  
       }else{  
         $msg="Please enter valid login details. ".$time_remain. " attempts remains";  
       }  
       //Data insert into attempt_count table  
       mysqli_query($conn,"INSERT INTO `attempt_count`(`ip_address`, `time_count`) VALUES ('$ip_address','$time')");  
       //Error Message display after enter wrong details  
       //$msg="Please enter valid login details.";  
     }  
   }  
 }  
 //Get proper User IP Address  
 function getUserIpAddr(){  
   if(!empty($_SERVER['HTTP_CLIENT_IP'])){  
     $ip = $_SERVER['HTTP_CLIENT_IP'];  
   }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){  
     $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
   }else{  
     $ip = $_SERVER['REMOTE_ADDR'];  
   }  
   return $ip;  
 }  
 ?>  
 <style type="text/css">  
   .error{  
     color: red;  
     font-weight: bold;  
   }  
 </style>  
 <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">  
 <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>  
 <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
 <!------ Include the above in your HEAD tag ---------->  
 <!-- no additional media querie or css is required -->  
 <div class="container">  
     <div class="row justify-content-center align-items-center" style="height:100vh">  
       <div class="col-4">  
         <div class="card">  
           <div class="card-body">  
             <form action="" autocomplete="off" method="post">  
               <div class="form-group">  
                 <input type="text" class="form-control" name="username" placeholder="Username">  
               </div>  
               <div class="form-group">  
                 <input type="password" class="form-control" name="password" placeholder="Password">  
               </div>  
               <button type="submit" id="sendlogin" class="btn btn-primary" name="submit">login</button><br><br>  
               <div class="error"><?php echo $msg ?></div>  
             </form>  
           </div>  
         </div>  
       </div>  
     </div>  
   </div>  


dashboard.php

 <?php   
 session_start();  
 $conn=mysqli_connect("localhost","root","","tutorials");  
 if (!isset($_SESSION['USER_ID'])) {  
   header("location:login_form.php");  
   die();  
 }  
 ?>  
 <h1><?php echo "Welcome ". $_SESSION['USER_ID']; ?></h1>  
 <a href="logout.php">Logout</a>  


After a successful login user will redirect to this page. This page validates with the session if the session is the empty user will redirect to index.php page.

logout.php : This page used to destroy the session.

 <?php   
 session_start();  
 unset($_SESSION['USER_ID']);  
 header("location:login_form.php");  
 die();  
 ?>  


Username : admin

Password : admin

Post a Comment

0 Comments