PHP
PHP Login Rate Limiter (Session Based)
Adds a thin rate-limiting layer in front of your login handler. Counts attempts in the session, locks the form for a short window after too many failures, and returns clear error messages.
Usage notes
Use this at the top of your login handling script, before checking credentials.
- Adjust
$maxAttemptsand$lockSecondsto match your tolerance. - Works per-session; for heavier projects you can adapt the pattern to store attempts in a database keyed by IP or user ID.
Copy this snippet into your project
Use the full version for learning, or copy it without comments when you just want the bare code.
<?php
declare(strict_types=1);
session_start();
$maxAttempts = 5;
$lockSeconds = 900; // 15 minutes
$now = time();
$attempts = (int)($_SESSION['login_attempts'] ?? 0);
$lockedUntil = (int)($_SESSION['login_locked_until'] ?? 0);
if ($lockedUntil > $now) {
$remaining = $lockedUntil - $now;
http_response_code(429);
exit('Too many attempts. Please try again in ' . $remaining . ' seconds.');
}
// ... check username/password here ...
$loginOk = false; // replace with your actual check
if (!$loginOk) {
$attempts++;
$_SESSION['login_attempts'] = $attempts;
if ($attempts >= $maxAttempts) {
$_SESSION['login_locked_until'] = $now + $lockSeconds;
}
http_response_code(401);
exit('Invalid credentials.');
}
// Successful login: reset counters
unset($_SESSION['login_attempts'], $_SESSION['login_locked_until']);
// continue with your normal logged-in flow