Prevent user from login for 30 seconds after 3 failed login attempts – PHP
In this tutorial, we will teach you how you can prevent user from login for 30 seconds after they made 3 failed login attempts. We will be using PHP.
We will be saving a session variable of integer type, which will store the number of failed login attempts. So every time user enter the wrong password, we will increment this session variable. You can put your own condition to authenticate user in login_failed variable. $_SESSION is an built-in PHP array and it will automatically initialize some variable if is already not exists. You do not have to intialize variable “login_attempts”.
<?php
session_start();
if (login_failed)
{
$_SESSION["login_attempts"] += 1;
}
?>
Hide sign in button after 3 failed login attempts
Now, to block the user for 30 seconds after 3 failed attempts and un-block him after 30 seconds, we need to perform the following steps:
- At login form submit button, first check if number of failed attempts is 3 or greater than 3.
- Then we store current time in separate session variable named “locked”.
- And at the top of page, check if the user is locked out.
- Taking difference of current time and the time when user was locked out, will give the number of seconds.
- Check how many seconds has been passed since user was locked out ?
- If 30 seconds are passed, simply remove all the session variables we created.
<?php
session_start();
// At the top of page right after session_start();
if (isset($_SESSION["locked"]))
{
$difference = time() - $_SESSION["locked"];
if ($difference > 30)
{
unset($_SESSION["locked"]);
unset($_SESSION["login_attempts"]);
}
}
// In sign-in form submit button
if ($_SESSION["login_attempts"] > 2)
{
$_SESSION["locked"] = time();
echo "Please wait for 30 seconds";
}
else
{
?>
<button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button>
<?php
}
?>
Conclusion
This technique is very useful to prevent brute force attack. Because hacker may try to guess all possible combination of password and run an automatic script to automatically fill the login form with different passwords. In this case, submit button will be hidden after 3 failed login attempts for 30 seconds. Thus it will break the script.
Also it will be useful to prevent DOS (Denial Of Service) attack, which means hacker may try to automatically send a large number of login requests which may slow down your server. But if the submit button was hidden after 3 requests, then it will also break that script.
That’s how you can prevent user from login for 30 seconds after they made 3 failed login attempts in PHP.
[wpdm_package id=’231′]
abc
Amazing!