How can PHP be used to implement a form lockout after a certain number of failed attempts?

To implement a form lockout after a certain number of failed attempts in PHP, you can keep track of the number of failed attempts in a session variable. Once the number of failed attempts exceeds a certain threshold, you can prevent further form submissions for a specified period of time before allowing the user to try again.

session_start();

$failedAttempts = isset($_SESSION['failedAttempts']) ? $_SESSION['failedAttempts'] : 0;
$maxAttempts = 3;
$lockoutPeriod = 60; // seconds

if ($failedAttempts >= $maxAttempts) {
    $lockoutUntil = time() + $lockoutPeriod;
    $_SESSION['lockoutUntil'] = $lockoutUntil;
    
    if (time() < $lockoutUntil) {
        die("Account locked. Please try again later.");
    } else {
        $_SESSION['failedAttempts'] = 0;
    }
}

// Check login credentials
if ($loginFailed) {
    $_SESSION['failedAttempts'] = ++$failedAttempts;
    // Handle login failure
} else {
    // Handle successful login
}