October 10, 2024

PHP: Block access for specific IP addresses

Ever had a Spambot on your site? Cleaning up the database after a spam attack is a tedious task.

One way to avoid this is designing your webforms more complicated, so automatic spam bots are not able to fill them out. This works in most cases, but has a negative impact on the usability of the site. And one day a spambot even gets through your more difficult web form and the game begins again.

An interesting observation is, that spam bots are not as clever as one might think. On our web projects, we observed, that spam bots tend to access from the same IP adress again and again. Therefore, the simplest way to avoid spam is to block that IP adress.

See here how the PHP Code for this can look like:

<?php
    $IP_denylist = 
    //Enter here the IP adresses the Spam bot uses 
    array("123.456.789.00", "987.654.321.00");
    if (in_array($_SERVER['REMOTE_ADDR'], $IP_denylist)) {
        header("location: http://www.google.com/"); //You can forward here to any site
        exit();
    }
?>

Simply enter the IP adresses in the array and access from these IP adresses will be forwarded. The shown code should be placed at the beginning of your PHP document.

Further information

These articles could also be of your interest:

This article is also available in German language:

Leave a Reply

Your email address will not be published. Required fields are marked *