Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

How to Block IP Addresses with PHP

[ Image: Skeletor Blocks a Move ] Figuratively speaking, hunting down and killing spammers, scrapers, and other online scum remains one of our favorite pursuits. Once we have determined that a particular IP address is worthy of banishment, we generally invoke the magical powers of htaccess to lock the gates. When htaccess is not available, we may summon the versatile functionality of PHP to get the job done.

This method is straightforward. Simply edit, copy and paste the following code example into the top of any PHP for which you wish to block access:

<?php $deny = array("111.111.111", "222.222.222", "333.333.333");
if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) {
   header("location: https://example.com/");
   exit();
} ?>

The code basically creates an array of the IP addresses that you wish to block, and then checks incoming addresses against the array. If the incoming (i.e., remote) address matches against any value in the array, the function will deny access with a redirect header to the specified URL, which in this case is the majestic Google home page. It all happens quickly behind the scenes.

Usage

When using this code in your pages, simply replace the “dummy” IP addresses (i.e., "111.111.111", "222.222.222", ...) with those that you wish to block (e.g., "123.456.789", "123.456.*", "123.*", ...). Yes, PHP understands wildcard operators (i.e., *). Also you may want to change the redirect location. Currently it is set to https://example.com/, so feel free to change that to whatever URL is desired.

After making any changes, upload the file to your server. If you would like to verify this method, simply lookup your own IP address, add it to the array, and try loading the target page. That’s all there is to it — “grab, gulp, and go”.

Using this method, you may also wish to create a customized page to which blocked addresses are redirected, perhaps to explain the situation, provide contact information, or display a macro shot of your greasy bum, or perhaps send them to the blackhole.

About the Author
Jeff Starr = Creative thinker. Passionate about free and open Web.
Blackhole Pro: Trap bad bots in a virtual black hole.

109 responses to “How to Block IP Addresses with PHP”

  1. Awesome. It worked. Thank you very much. I posted a link to your site on Elgg.org

  2. Ok I know absolutely nothing about html or code writing, but I need to block a handful of IP addresses that have been harassing me. I’ve been tracking their activity on my site using StatCounter. I tried using Toolator.com but they only let me block 3 addresses for free. Is there anything I can paste into my template html code that will ban these addresses?

  3. Hi,

    I need code that will block every IP address, then allow me to add just a few that are allowed. I have been looking on Google for hours, and can’t find what I’m looking for. I can’t access the directory, so .htaccess is out, but I can cut/paste PHP code.

    Is this possible?

    Thank you in advance.

    Leslie

  4. @Leslie

    Check out Taniguchi’s post. You can add the IP’s you wnat to block on the list using wild cards. But if you want to allow JUST a few IPs, it’s simple. Create a method to validate the IP you want to allow. Ex.: (note that the sample below returns TRUE is IP is allowed and FALSE if not.). To use just call:

    Hope it helps

  5. Sorry to double post but the code its just gone….

    ### USAGE

    if(allowedIP()) {
         // do something for allowed IP
    } else {
         // do something else
    }

    function allowedIP() {
         $accessIP[] = '127.0.0.1' ; // the ip you want to allow
         $accessIP[] = '127.0.0.2' ;

         $userIP = $_SERVER['REMOTE_ADDRESS'];

         $trackReturn = false;

         for($i=0; $i < count($accessIP); $i++) {
         if($accessIP[$i] == $userIP) {
              $trackReturn = true;
         }
         }
         return $trackReturn;
    }

  6. I actually tried the temporary re-direct instead, as that seemed to be a solution I could implement, but it didn’t work. It must be the program I’m using to do my webpage. I’m anything but saavy when it comes to this stuff. I use SiteBuilder, from Homestead, and that must be my problem. =(

  7. if you need any further help with that, call me on skype@isynapps. I have no experience with site builder but I can code….a little :)

  8. I do still need a solution, but I hate to take up your time this way. You’re very generous. If you are up for it, what I need is something that, when a person clicks a link to visit a restricted page, if their IP address is not on the approved list, they are re-directed to another page. SiteBuilder will allow an html string to be pasted into the page, but not PHP, nor .htaccess. I can’t get to the actual directory where I would put these files. If this is possible with html code, and you’re up for it, I’ll call. Thank you again for your generosity. I’m grateful.

  9. I got a couple of questions so I can better figure your problem:

    Are you talking about Yahoo SiteBuilder?
    what is the filename? [.html, .htm, .php]?
    are you allowed to use PHP at all?

    Just to let you know, you can’t perform server-side interaction with just html. If you’re not allowed to code PHP, it will be a little hard to get it done. An alternative is deploying a flex based app to validate the user for you. because flex frameworks runs as stand-alone within flash player, you could easily validate any type of info or even query database within html enviroment.

  10. Answers to questions:

    It’s SiteBuilder through Homestead (well, it’s now Intuit, but it used to be Homestead).

    Not sure what you mean by ‘file’ name. I am allowed to insert html code through a ‘feature’ in SiteBuilder. I choose the feature, and insert the code. It then puts it in the page.

    I’m not sure about the use of PHP. It appears I have to open a directory to insert it, and ‘call’ it, but I’m unable to find these directories.

    I’m sure none of this is helpful. I’m sorry. I don’t really understand much of this, though I am doing a pretty fair job with the SiteBuilder app.

  11. by file name I mean index.html or index.php.
    I did some research about SiteBuilder. I found out that you can’t really use PHP on your pages. They use modules and alot of JS. You can use Javascript though.

  12. LOL…I don’t know to use that, either! Sigh…web page work is not for the technically challenged! Where might I find some information about Javascript to do what I need, if you don’t mind my asking?

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
GA Pro: Add Google Analytics to WordPress like a pro.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.