How to Limit a Login Attempt Validation using PHP

This tutorial tackles on how to create a login attempt validation using PHP. If you want to temporarily block a user from logging in to your site after a 3 or more unsuccessful login, this simple tutorial will teach you how to do that using a PHP session. The attempts validation will only count if the username exists on the database but entered the wrong password.

Getting Started

In order to beautify the presentation of this tutorial, I've used Bootstrap which is included in the downloadable of this tutorial but if you want, you can download Bootstrap using this link.

Create the Database

Open your PHPMyAdmin and create a new databse naming dbase. Then navigate to database SQL Tab and paste the SQL script below.

  1.         CREATE TABLE `users` (
  2.           `id` int(11) NOT NULL,
  3.           `username` varchar(50) NOT NULL,
  4.           `password` varchar(60) NOT NULL
  5.         ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  6.  
  7.         INSERT INTO `users` (`id`, `username`, `password`) VALUES
  8.         (1, 'nurhodelta', '$2y$10$AP027M5jhULJPIBAUiCa0e0phP1UAQBlKqTLLQZ2.UL44x5DdUwHq');
  9.  
  10.         ALTER TABLE `users`
  11.         ADD PRIMARY KEY (`id`);
  12.  
  13.         ALTER TABLE `users`
  14.         MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

Creating our Login Form

Next, we create our login form by creating a new file, name it as index.php and paste the codes below.

  1. <?php
  2.         session_start();
  3.         //check if can login again
  4.         if(isset($_SESSION['attempt_again'])){
  5.                 $now = time();
  6.                 if($now >= $_SESSION['attempt_again']){
  7.                         unset($_SESSION['attempt']);
  8.                         unset($_SESSION['attempt_again']);
  9.                 }
  10.         }
  11.        
  12. ?>
  13. <!DOCTYPE html>
  14. <html>
  15. <head>
  16.         <meta charset="utf-8">
  17.         <title>How to Create a Login Attempt Validation using PHP</title>
  18.         <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  19. </head>
  20. <body>
  21. <div class="container">
  22.         <h1 class="page-header text-center">Login Attempt Validation using PHP</h1>
  23.         <div class="row">
  24.                 <div class="col-sm-4 col-sm-offset-4 panel panel-default" style="padding:20px;">
  25.                         <form method="POST" action="login.php">
  26.                                 <p class="text-center" style="font-size:25px;"><b>Login</b></p>
  27.                                 <hr>
  28.                                 <div class="form-group">
  29.                                         <label for="username">Username:</label>
  30.                                         <input type="text" name="username" id="username" class="form-control" placeholder="nurhodelta">
  31.                                 </div>
  32.                                 <div class="form-group">
  33.                                         <label for="password">Password:</label>
  34.                                         <input type="password" name="password" id="password" class="form-control" placeholder="malynisheart">
  35.                                 </div>
  36.                                 <button type="submit" name="login" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span> Login</button>
  37.                         </form>
  38.                         <?php
  39.                                 if(isset($_SESSION['error'])){
  40.                                         ?>
  41.                                         <div class="alert alert-danger text-center" style="margin-top:20px;">
  42.                                                 <?php echo $_SESSION['error']; ?>
  43.                                         </div>
  44.                                         <?php
  45.  
  46.                                         unset($_SESSION['error']);
  47.                                 }
  48.  
  49.                                 if(isset($_SESSION['success'])){
  50.                                         ?>
  51.                                         <div class="alert alert-success text-center" style="margin-top:20px;">
  52.                                                 <?php echo $_SESSION['success']; ?>
  53.                                         </div>
  54.                                         <?php
  55.  
  56.                                         unset($_SESSION['success']);
  57.                                 }
  58.                         ?>
  59.                 </div>
  60.         </div>
  61. </div>
  62. </body>
  63. </html>

Creating our Login Script

Lastly, we create our script that checks the user credential and temporarily disables a user after three unsuccessful login attempt.

Create a new file, name it as login.php and paste the codes below.

  1. <?php
  2.         session_start();
  3.  
  4.         if(isset($_POST['login'])){
  5.                 //connection
  6.                 $conn = new mysqli('localhost', 'root', '', 'dbase');
  7.  
  8.                 //set login attempt if not set
  9.                 if(!isset($_SESSION['attempt'])){
  10.                         $_SESSION['attempt'] = 0;
  11.                 }
  12.  
  13.                 //check if there are 3 attempts already
  14.                 if($_SESSION['attempt'] == 3){
  15.                         $_SESSION['error'] = 'Attempt limit reach';
  16.                 }
  17.                 else{
  18.                         //get the user with the email
  19.                         $sql = "SELECT * FROM users WHERE username = '".$_POST['username']."'";
  20.                         $query = $conn->query($sql);
  21.                         if($query->num_rows > 0){
  22.                                 $row = $query->fetch_assoc();
  23.                                 //verify password
  24.                                 if(password_verify($_POST['password'], $row['password'])){
  25.                                         //action after a successful login
  26.                                         //for now just message a successful login
  27.                                         $_SESSION['success'] = 'Login successful';
  28.                                         //unset our attempt
  29.                                         unset($_SESSION['attempt']);
  30.                                 }
  31.                                 else{
  32.                                         $_SESSION['error'] = 'Password incorrect';
  33.                                         //this is where we put our 3 attempt limit
  34.                                         $_SESSION['attempt'] += 1;
  35.                                         //set the time to allow login if third attempt is reach
  36.                                         if($_SESSION['attempt'] == 3){
  37.                                                 $_SESSION['attempt_again'] = time() + (5*60);
  38.                                                 //note 5*60 = 5mins, 60*60 = 1hr, to set to 2hrs change it to 2*60*60
  39.                                         }
  40.                                 }
  41.                         }
  42.                         else{
  43.                                 $_SESSION['error'] = 'No account with that username';
  44.                         }
  45.  
  46.                 }
  47.  
  48.         }
  49.         else{
  50.                 $_SESSION['error'] = 'Fill up login form first';
  51.         }
  52.  
  53.         header('location: index.php');
  54.  
  55. ?>

That's it! You can now test the code you created on your end. If there's an error occurred, please review your codes and check again my provided source code. You can also download the working source code I created for this tutorial. The download button is located below this tutorial.

That ends this tutorial. I hope this helps you with what you are looking for.

Happy Coding :)

Comments

Nice! still posting code. I'm always checking your profile to see new stuff.

The mechanism of creating limited attempts to log in is (in my believe) created to stop the brute forcing the password. If you made it based on Session then malicious user (or even normal one who knows how to use developer tools) can delete his session and start trying from start. The trick is that he must guess if it's Session based but it's easy to find out if you have Session just from trying to log in. So for me it's not secure enough and you should try to store the information where user can't access it like database or simple temporary file. It can be based on ip of user but this can be changed by proxy or because he changed his location.

So there is no 100% secure option (at least I don't know one) so the best we can do is to make it so hard to get in that the hacker will just give up.

What if the user deleted the whole session at the browser? Will it still wait for the remaining time if the user has attempted many times on logging in?

Username Pass?

This is totaly BAD and irelevant! Malicious hacker will not use same session but bruteattack with milions of requests/second with always new session... what a bad practice... You need at least IP throttle limit and this will slow down or lock out some IPs really fast.

Add new comment