subscribe via rss subscribe via mail subscribe via twitter

How To Block Multiple IP Addresses Using PHP

Posted in PHP, October 20th, 2009 and has 7 comments

PHP Book

Sometimes you need to disallow a visitor to access your website. The most common reason for this is Spammers. Although there are several other solutions to block multiple IP addresses such as using Apache’s mod_rewrite which I am going to write about it soon. but today I am going to focus on the method of PHP.

Now, Let’s start the code from the beginning.

Step One: Adding The IPs

<?php
// The blacklisted IPs.
$denied_ips = array(
		    '123.456.789.1',
		    '127.0.0.1',
		    '67.220.200.75'
		);

I opened a PHP tag and then created a variable named $denied_ips contains an array of the 3 assigned values which are the IPs we are dealing with. Also you may want to use an external file rather than opening this PHP file every time you want to edit the IPs. it’s easy, just create a new file name it “blacklist.txt” or whatever, and put the IPs that you want to disallow. Another thing you have to do is to change the code to this.

// The blacklisted ips.
$denied_ips = file('ips.txt');

Step Two: Getting The Visitor’s IP

// Function to get the visitor's IP.
function getUserIP()
{
    //check ip from share internet
    if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    //to check ip is pass from proxy
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
	return $ip;
}

//The user IP
$visitorIp = getUserIP();

This is the function we are going to use to get the IP of the visitor. Some people just like to use $_SERVER['REMOTE_ADDR'] which is fine but i believe by this method we will get more accurate data. Also i have assigned the variable $visitorIp to the function getUserIP().

Edit: Using $_SERVER['HTTP_X_FORWARDED_FOR'] to detect the IP could be useless sometimes. And even a reason to grant access to the visitor since it can be modified. So you can just use:

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

//The user IP
$visitorIp = getUserIP();

Step Three: Matching The IPs

// Now let's search if this IP is blackliated
$status = array_search($visitorIp, $denied_ips);

// Let's check if $status has a true OR false value.
if($status !== false)
    {
	echo "YOUR IP HAS BEEN BANNED.";
	// header("Location: http://zombo.com");
	exit;
    }

In the code above the function array_search Searches the array for a given value and returns the corresponding key if successful. So the variable $status is Boolean, if it’s true the program will stop and print “YOUR IP HAS BEEN BANNED”. Otherwise the script will work normally. the redirection to zombo.com is just for irony.

the Complete Code

<?php
// The blacklisted ips.
$denied_ips = array(
		    '123.456.789.1',
		    '127.0.0.1',
		    '67.220.200.75'
		);

// The function to get the visitor's IP.
function getUserIP()
{
    //check ip from share internet
    if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    //to check ip is pass from proxy
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
	return $ip;
}

//The user
$visitorIp = getUserIP();

// Now let's search if this IP is blackliated
$status = array_search($visitorIp, $denied_ips);

// Let's check if $status has a true OR false value.
if($status !== false)
    {
	echo "YOUR IP HAS BEEN BANNED.";
	// header("Location: http://zombo.com");
	exit;
    }
?>

Conclusion

Even though this is mostly used to block IPs from a particular website, it can be used in some other ideas as to verify if the user has only one account and so on. I hope you enjoyed this tutorial and thanks for reading. If you you have anything to say please leave it in the comments section below.

Author

Mohamed Amine is a university student. He lives in Algeria, Algiers. He is interested in PHP, jQuery, and Css. He likes to play Bowling and Pool. You can follow him on Twitter and Facebook.

What's next? Help us to share this.

Comments

Want to show an avatar in your the comments? Join Gravatar.
  • G Mali said:

    nice idea…but wouldn’t the hackers just change locations??? lol

  • @G Mali
    Yes, that is true. This isn’t the right solution for big projects but it can be useful in a multi-membership system with cookies. I guess you would like to read about http://en.wikipedia.org/wiki/Iptables

  • Slyy said:

    Why using array_search when in_array is enough?
    You don’t want to retrieve the corresponding key for further work, you just want to know if the current IP is IN the blacklisted array…

  • @Slyy
    Yes, that is right. at the beginning i was planning to make the output like that.

    echo "YOUR IP " . $status . " HAS BEEN BANNED.";
    

    but eventually I figured out that i can just call the $visitorIp instead of $status. Thanks for the notice. but it works with both ways.

  • revive said:

    Great post! I implemented it, but for some reason it wasn’t catching any IPs (tested by blocking my own and echo’ing it in the page).. so, I changed the getUserIp function to this:

    function getUserIP()
    {
    $alt_ip = $_SERVER['REMOTE_ADDR'];

    if (isset($_SERVER['HTTP_CLIENT_IP']))
    {
    $alt_ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all(‘#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s’, $_SERVER['HTTP_X_FORWARDED_FOR'], $matches))
    {
    // make sure we dont pick up an internal IP defined by RFC1918
    foreach ($matches[0] AS $ip)
    {
    if (!preg_match(“#^(10|172\.16|192\.168)\.#”, $ip))
    {
    $alt_ip = $ip;
    break;
    }
    }
    }
    else if (isset($_SERVER['HTTP_FROM']))
    {
    $alt_ip = $_SERVER['HTTP_FROM'];
    }

    return $alt_ip;
    }

    and it works great !!

    Thanks again.

Follow Discussion

Trackbacks

Leave a Reply