How to limit login attempt Using PHP and MySQL
In this tutorial, we will learn, How to limit the login attempt using PHP and MySQL.
File structure and database tables used in this tutorial:
Two MySQL Tables used:
- loginlogs (This table stores user login IP address and login attempt time )
- user (User 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)
loginlogs MySQL table structure:
1 2 3 4 5 |
CREATE TABLE `loginlogs` ( `id` int(11) NOT NULL, `IpAddress` varbinary(16) NOT NULL, `TryTime` bigint(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; |
user MySQL table structure:
1 2 3 4 5 |
CREATE TABLE `user` ( `id` int(11) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; |
config.php: This file is used for the database connection.
1 2 3 4 5 6 7 |
<?php $con=mysqli_connect("localhost","root","","loginattemp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<form id="login-form" class="form" method="post"> <div class="form-group"> <label for="username" class="text-info">Username:</label><br> <input type="text" name="username" id="username" class="form-control" required> </div> <div class="form-group"> <label for="password" class="text-info">Password:</label><br> <input type="password" name="password" id="password" class="form-control" required> </div> <div class="form-group"> <input type="submit" name="submit" class="btn btn-info btn-md" value="Submit"> </div> <div id="result"><?php echo $msg?></div> </form> |
Now create a function for IP address
1 2 3 4 5 6 7 8 9 10 |
function getIpAddr(){ if (!empty($_SERVER['HTTP_CLIENT_IP'])){ $ipAddr=$_SERVER['HTTP_CLIENT_IP']; }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ $ipAddr=$_SERVER['HTTP_X_FORWARDED_FOR']; }else{ $ipAddr=$_SERVER['REMOTE_ADDR']; } return $ipAddr; } |
We will store the IP address in a variable and also create a variable for time.
1 2 |
$time=time()-30; // Here you can chnage the attempt lock time. We using 30 here because after 3 failed login attempt, user can't login for 30 second. $ip_address=getIpAddr(); // Stroing IP address in a variable. |
After this, we will get the login attempt count on the basis of IP address and Try time.
1 2 3 |
$query=mysqli_query($con,"select count(*) as total_count from loginlogs where TryTime > $time and IpAddress='$ip_address'"); $check_login_row=mysqli_fetch_assoc($query); $total_count=$check_login_row['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/>$rem_attm attempts remaining”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
//Checking if the attempt 3, or youcan set the no of attempt her. For now we taking only 3 fail attempted if($total_count==3){ $msg="To many failed login attempts. Please login after 30 sec"; }else{ //Getting Post Values $username=$_POST['username']; $password=md5($_POST['password']); // Coding for login $res=mysqli_query($con,"select * from user where username='$username' and password='$password'"); if(mysqli_num_rows($res)){ $_SESSION['IS_LOGIN']='yes'; mysqli_query($con,"delete from loginlogs where IpAddress='$ip_address'"); echo "<script>window.location.href='dashboard.php';</script>"; }else{ $total_count++; $rem_attm=3-$total_count; if($rem_attm==0){ $msg="To many failed login attempts. Please login after 30 sec"; }else{ $msg="Please enter valid login details.<br/>$rem_attm attempts remaining"; } $try_time=time(); mysqli_query($con,"insert into loginlogs(IpAddress,TryTime) values('$ip_address','$try_time')"); } } |
Here is the full code that we have written for index.php page:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
<?php session_start(); include_once('config.php'); $msg=''; if(isset($_POST['submit'])){ $time=time()-30; $ip_address=getIpAddr(); // Getting total count of hits on the basis of IP $query=mysqli_query($con,"select count(*) as total_count from loginlogs where TryTime > $time and IpAddress='$ip_address'"); $check_login_row=mysqli_fetch_assoc($query); $total_count=$check_login_row['total_count']; //Checking if the attempt 3, or youcan set the no of attempt her. For now we taking only 3 fail attempted if($total_count==3){ $msg="To many failed login attempts. Please login after 30 sec"; }else{ //Getting Post Values $username=$_POST['username']; $password=md5($_POST['password']); // Coding for login $res=mysqli_query($con,"select * from user where username='$username' and password='$password'"); if(mysqli_num_rows($res)){ $_SESSION['IS_LOGIN']='yes'; mysqli_query($con,"delete from loginlogs where IpAddress='$ip_address'"); echo "<script>window.location.href='dashboard.php';</script>"; }else{ $total_count++; $rem_attm=3-$total_count; if($rem_attm==0){ $msg="To many failed login attempts. Please login after 30 sec"; }else{ $msg="Please enter valid login details.<br/>$rem_attm attempts remaining"; } $try_time=time(); mysqli_query($con,"insert into loginlogs(IpAddress,TryTime) values('$ip_address','$try_time')"); }} } // Getting IP Address function getIpAddr(){ if (!empty($_SERVER['HTTP_CLIENT_IP'])){ $ipAddr=$_SERVER['HTTP_CLIENT_IP']; }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ $ipAddr=$_SERVER['HTTP_X_FORWARDED_FOR']; }else{ $ipAddr=$_SERVER['REMOTE_ADDR']; } return $ipAddr; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="robots" content="noindex, nofollow"> <title>Login Form</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <style type="text/css"> body {margin: 0;padding: 0;background-color: #b81e17;height: 100vh;} #login .container #login-row #login-column #login-box {margin-top: 60px;max-width: 600px;height: 320px;border: 1px solid #9C9C9C;background-color: #EAEAEA;} #login .container #login-row #login-column #login-box #login-form {padding: 40px;} #result{color:red;} </style> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <body> <div id="login"> <h3 class="text-center text-white pt-5">Login form</h3> <div class="container"> <div id="login-row" class="row justify-content-center align-items-center"> <div id="login-column" class="col-md-6"> <div id="login-box" class="col-md-12"> <form id="login-form" class="form" method="post"> <div class="form-group"> <label for="username" class="text-info">Username:</label><br> <input type="text" name="username" id="username" class="form-control" required> </div> <div class="form-group"> <label for="password" class="text-info">Password:</label><br> <input type="password" name="password" id="password" class="form-control" required> </div> <div class="form-group"> <input type="submit" name="submit" class="btn btn-info btn-md" value="Submit"> </div> <div id="result"><?php echo $msg?></div> </form> </div> </div> </div> </div> </div> </body> </html> |
dashboard.php
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php session_start(); if(!isset($_SESSION['IS_LOGIN'])){ ?> <script> window.location.href='index.php'; </script> <?php }else{ echo "Welcome"; } ?> || <a href="logout.php">Logout</a> |
logout.php: This page used to destroy the session.
1 2 3 4 5 6 7 8 |
<?php session_start(); unset($_SESSION['IS_LOGIN']); session_destroy(); ?> <script> window.location.href='index.php'; </script> |
View Demo—————————————————————————
Username: admin
Password: Test@123