How can PHP be used to implement a temporary IP blacklist for users who exceed a certain number of login attempts?

To implement a temporary IP blacklist for users who exceed a certain number of login attempts, we can use PHP to track the number of failed login attempts for each IP address and block access if the threshold is reached. This can help prevent brute force attacks on the login system.

<?php
// Define the maximum number of login attempts before IP is blacklisted
$maxAttempts = 5;

// Get the user's IP address
$ip = $_SERVER['REMOTE_ADDR'];

// Check if IP is already blacklisted
if (file_exists('blacklist.txt')) {
    $blacklist = file_get_contents('blacklist.txt');
    $blacklist = explode("\n", $blacklist);
    if (in_array($ip, $blacklist)) {
        die('Your IP is temporarily blacklisted. Please try again later.');
    }
}

// Check if login attempts for this IP exceed the threshold
$attemptsFile = 'attempts_' . $ip . '.txt';
if (file_exists($attemptsFile)) {
    $attempts = file_get_contents($attemptsFile);
} else {
    $attempts = 0;
}

if ($attempts >= $maxAttempts) {
    file_put_contents('blacklist.txt', $ip . "\n", FILE_APPEND);
    die('Your IP has been temporarily blacklisted due to multiple failed login attempts.');
}

// Process login attempt
// If login fails, increment the attempts counter
if ($loginFailed) {
    $attempts++;
    file_put_contents($attemptsFile, $attempts);
}

?>