How can logging login attempts help in identifying and preventing spam or unauthorized access in PHP applications?

Logging login attempts can help in identifying patterns of spam or unauthorized access by tracking the frequency, source, and success rates of login attempts. By analyzing this information, developers can implement measures such as rate limiting, CAPTCHA challenges, or IP blocking to prevent malicious activities.

// Log login attempts
function logLoginAttempt($username, $success) {
    $logFile = 'login_attempts.log';
    $logMessage = date('Y-m-d H:i:s') . ' - Username: ' . $username . ' - Success: ' . ($success ? 'Yes' : 'No') . PHP_EOL;
    file_put_contents($logFile, $logMessage, FILE_APPEND);
}

// Example usage
$username = 'example_user';
$success = true; // or false if login failed
logLoginAttempt($username, $success);