Search code examples
php.htaccessip-addressblock

Block ip addresses automatically using PHP and htaccess


I have a login system that I am trying to make as secure as possible. After ten failed attempts, I would like to block the IP address. How can I open a file in PHP and add a line to my .htaccess file to block the IP Address? Here is my .htaccess file:

# Turn on RewriteEngine
RewriteEngine on

# Block IP addresses with too many failed attempts
RewriteCond %{REMOTE_ADDR} ^217.172.179.*$ [OR]
RewriteCond %{REMOTE_ADDR} ^217.172.180.*$
RewriteCond %{REQUEST_URI} !/error/blocked.php$ [NC]
RewriteRule ^(.*)$ /error/blocked.php [R,NC,L]

I would like the PHP file to add the line:

RewriteCond %{REMOTE_ADDR} ^IPHERE$ [OR]

in the appropriate spot.


Solution

  • I wouldn't recommend editing the .htaccess file directly.

    Instead, have a file or a database table to save all of the blacklisted IP addresses, and test against that in PHP, rather than on Apache's side.