Get a Pentest and security assessment of your IT network.

Cyber Security

PHP: Stop Brute Force Attacks

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

  1. 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.
  2. 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).
  3. Check for Existing Block: Before processing any login attempts, check if the user is already blocked.
  4. Count Failed Attempts: If the login fails (or any request is incorrect), increment the attempt counter in the session.

    Replace $login_failed with the actual variable that indicates a failed login.

  5. 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
    }
    ?>
  6. Reset Counter on Success: If the login is successful (or the request is valid), reset the attempt counter.

    Replace $login_successful with the actual variable that indicates a successful login.

  7. 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.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation