How can PHP code be structured to implement a lock timeout for user login attempts?

To implement a lock timeout for user login attempts in PHP, you can store the number of failed login attempts in a session variable and check if it exceeds a certain threshold before locking the user out for a specified period. You can use a timestamp to track when the lockout started and compare it against the current time to determine if the lockout period has elapsed.

session_start();

$lockoutThreshold = 3; // Number of failed login attempts before lockout
$lockoutDuration = 60; // Lockout duration in seconds

if(isset($_SESSION['login_attempts']) && $_SESSION['login_attempts'] >= $lockoutThreshold) {
    if(isset($_SESSION['lockout_start']) && time() - $_SESSION['lockout_start'] < $lockoutDuration) {
        echo "Account locked. Please try again later.";
        exit();
    } else {
        // Reset login attempts and lockout start time
        $_SESSION['login_attempts'] = 0;
        unset($_SESSION['lockout_start']);
    }
}

// Check user login credentials
if($login_successful) {
    // Reset login attempts on successful login
    $_SESSION['login_attempts'] = 0;
} else {
    // Increment login attempts
    $_SESSION['login_attempts'] = isset($_SESSION['login_attempts']) ? $_SESSION['login_attempts'] + 1 : 1;
    
    // Set lockout start time if threshold is reached
    if($_SESSION['login_attempts'] >= $lockoutThreshold) {
        $_SESSION['lockout_start'] = time();
    }
}