TL;DR
This guide shows you how to block many failed login attempts (or other repeated wrong requests) using PHP sessions and a simple counter. It prevents attackers from trying thousands of passwords quickly.
How it Works
We’ll store the number of incorrect attempts in a PHP session variable. If this count goes above a certain limit, we temporarily block further access. After a set time, the counter resets automatically.
Step-by-Step Guide
- Start a Session: Make sure you start a PHP session at the very beginning of your script (before any HTML output). This is essential for storing the attempt count.
- Define Limits: Set two variables:
$maxAttempts: The maximum number of failed attempts allowed. A good starting value is 5 or 10.$blockDuration: How long to block access in seconds (e.g., 60 for one minute, 300 for five minutes).
- Check for Existing Block: Before processing any login attempts, check if the user is already blocked.
- Count Failed Attempts: If the login fails (or any request is incorrect), increment the attempt counter in the session.
Replace
$login_failedwith the actual variable that indicates a failed login. - Block Access: Check if the attempt count exceeds the maximum allowed. If it does, block access.
= $maxAttempts) { echo 'Account temporarily locked due to too many failed attempts.'; exit(); // Stop further execution } ?> - Reset Counter on Success: If the login is successful (or the request is valid), reset the attempt counter.
Replace
$login_successfulwith the actual variable that indicates a successful login. - Session Handling: Remember that sessions rely on cookies. Ensure your website is configured correctly for session handling and cookie security (e.g., using HTTPS).
Important Considerations
- Rate Limiting: This method blocks *after* multiple failed attempts. For better protection, consider implementing rate limiting to slow down requests before they even reach the login form.
- IP Blocking: You could also store and block IP addresses that exceed the attempt limit, but be careful about blocking legitimate users sharing an IP address.
- Database Logging: Log failed attempts (including timestamps and IPs) to a database for auditing and analysis.
- Security Best Practices: This is just one layer of security. Always use strong passwords, input validation, output encoding, and other cybersecurity measures.

