How To Block Multiple IP Addresses Using PHP?

Feb 20, 2015, by admin

Sometimes we need to ban particular visitors to access our website. For this, the most common reason is spammers and scrapers that perform malicious activity from few persistent IP addresses. Although there are so many tricks to block multiple IP addresses such as using htaccess, Apache mod_rewrite but here you’ll know the simple trick to block multiple IP addresses using PHP

block

Now, we’ll start the code from the beginning by defining an array which contains the IPs you want to block and call out the blockIP() function to block defined IPs.

// Define an array which contains the ip’s you want to block
$block_ip_list = array(
            ‘127.0.0.1’,
            ‘127.0.0.2’,
            ‘127.0.0.3’
        );
// Call out the function to block IPs
blockIP($block_ip_list);

Now we’ll define the function to get the IP of the visitor. The function will return IP address of visitors.

// Function to get the visitor’s IP.
function getVisitorIP()
{
    //check ip from share internet
    if (!empty($_SERVER[‘HTTP_CLIENT_IP’]))
    {
      $ip=$_SERVER[‘HTTP_CLIENT_IP’];
    }
    else
    {
      $ip=$_SERVER[‘REMOTE_ADDR’];
    }
    return $ip;
}

Finally we’ve a function to block visitor IPs. The function will get visitor IP address using getVisitorIP() function and checked visitor IP in $block_ip_list, if it is find then that IP will be blocked for that website.

// Function to block IP.
function blockIP($block_ip_list){
    $ip = getVisitorIP();
    if(in_array($ip, $block_ip_list)){
        die(“Your IP(” . $ip . “) has been blocked !”);
    }
}

Below is complete code with functions to block IP address.

// Function to get the visitor’s IP.
function getVisitorIP()
{
    //check ip from share internet
    if (!empty($_SERVER[‘HTTP_CLIENT_IP’]))
    {
      $ip=$_SERVER[‘HTTP_CLIENT_IP’];
    }
    else
    {
      $ip=$_SERVER[‘REMOTE_ADDR’];
    }
    return $ip;
}

// Function to block IP.
function blockIP($block_ip_list){
    $ip = getVisitorIP();
    if(in_array($ip, $block_ip_list)){
        die(“Your IP(” . $ip . “) has been blocked !”);
    }
}

// define an array which contains the ip’s you want to block
$block_ip_list = array(
            ‘127.0.0.1’,
            ‘127.0.0.2’,
            ‘127.0.0.3’
        );

// Call out the function to block IPs
blockIP($block_ip_list);

This is simple code to block particular IPs for a website. You can also use this code in some other cases such as track website visitors etc.