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
  6. INSERT INTO `users` (`id`, `username`, `password`) VALUES
  7. (1, 'nurhodelta', '$2y$10$AP027M5jhULJPIBAUiCa0e0phP1UAQBlKqTLLQZ2.UL44x5DdUwHq');
  9. ALTER TABLE `users`
  10. ADD PRIMARY KEY (`id`);
  12. ALTER TABLE `users`

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. //check if can login again
  3. if(isset($_SESSION['attempt_again'])){
  4. $now = time();
  5. if($now >= $_SESSION['attempt_again']){
  6. unset($_SESSION['attempt']);
  7. unset($_SESSION['attempt_again']);
  8. }
  9. }
  11. ?>
  12. <!DOCTYPE html>
  13. <html>
  14. <head>
  15. <meta charset="utf-8">
  16. <title>How to Create a Login Attempt Validation using PHP</title>
  17. <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  18. </head>
  19. <body>
  20. <div class="container">
  21. <h1 class="page-header text-center">Login Attempt Validation using PHP</h1>
  22. <div class="row">
  23. <div class="col-sm-4 col-sm-offset-4 panel panel-default" style="padding:20px;">
  24. <form method="POST" action="login.php">
  25. <p class="text-center" style="font-size:25px;"><b>Login</b></p>
  26. <hr>
  27. <div class="form-group">
  28. <label for="username">Username:</label>
  29. <input type="text" name="username" id="username" class="form-control" placeholder="nurhodelta">
  30. </div>
  31. <div class="form-group">
  32. <label for="password">Password:</label>
  33. <input type="password" name="password" id="password" class="form-control" placeholder="malynisheart">
  34. </div>
  35. <button type="submit" name="login" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span> Login</button>
  36. </form>
  37. <?php
  38. if(isset($_SESSION['error'])){
  39. ?>
  40. <div class="alert alert-danger text-center" style="margin-top:20px;">
  41. <?php echo $_SESSION['error']; ?>
  42. </div>
  43. <?php
  45. unset($_SESSION['error']);
  46. }
  48. if(isset($_SESSION['success'])){
  49. ?>
  50. <div class="alert alert-success text-center" style="margin-top:20px;">
  51. <?php echo $_SESSION['success']; ?>
  52. </div>
  53. <?php
  55. unset($_SESSION['success']);
  56. }
  57. ?>
  58. </div>
  59. </div>
  60. </div>
  61. </body>
  62. </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
  3. if(isset($_POST['login'])){
  4. //connection
  5. $conn = new mysqli('localhost', 'root', '', 'dbase');
  7. //set login attempt if not set
  8. if(!isset($_SESSION['attempt'])){
  9. $_SESSION['attempt'] = 0;
  10. }
  12. //check if there are 3 attempts already
  13. if($_SESSION['attempt'] == 3){
  14. $_SESSION['error'] = 'Attempt limit reach';
  15. }
  16. else{
  17. //get the user with the email
  18. $sql = "SELECT * FROM users WHERE username = '".$_POST['username']."'";
  19. $query = $conn->query($sql);
  20. if($query->num_rows > 0){
  21. $row = $query->fetch_assoc();
  22. //verify password
  23. if(password_verify($_POST['password'], $row['password'])){
  24. //action after a successful login
  25. //for now just message a successful login
  26. $_SESSION['success'] = 'Login successful';
  27. //unset our attempt
  28. unset($_SESSION['attempt']);
  29. }
  30. else{
  31. $_SESSION['error'] = 'Password incorrect';
  32. //this is where we put our 3 attempt limit
  33. $_SESSION['attempt'] += 1;
  34. //set the time to allow login if third attempt is reach
  35. if($_SESSION['attempt'] == 3){
  36. $_SESSION['attempt_again'] = time() + (5*60);
  37. //note 5*60 = 5mins, 60*60 = 1hr, to set to 2hrs change it to 2*60*60
  38. }
  39. }
  40. }
  41. else{
  42. $_SESSION['error'] = 'No account with that username';
  43. }
  45. }
  47. }
  48. else{
  49. $_SESSION['error'] = 'Fill up login form first';
  50. }
  52. header('location: index.php');
  54. ?>

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 :)


Nice! still posting code. I'm always checking your profile to see new stuff.
Submitted byMortimer333 (not verified)on Thu, 01/02/2020 - 22:54

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.

Submitted byjust a tech (not verified)on Thu, 09/02/2021 - 13:30

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?
Submitted byRadoslav Smerek (not verified)on Fri, 08/12/2022 - 18:09

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