Plugin Sale! Save 15% on pro plugins with discount code: NEWYEAR2021
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.

Jeff Starr
About the Author
Jeff Starr = Web Developer. Book Author. Secretly Important.
Banhammer: Protect your WordPress site against threats.

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

  1. I have found that your code doesn’t work well with wildcards at all. I still use the in_array() function check because for exact matches it is quicker but if you are blocking a range of IPs with wildcards then you need to use the eregi() function and check each item in your array separately for example:
    [ Editor’s note: code example gobbled by WordPress ]

  2. Jeff Starr
    Perishable 2007/10/17 7:33 am

    JRSofty,
    Please repost! Your code example was gobbled up by WordPress.. Either wrap each line in <code> tags or enclose the whole lot in both pre and code tags: <pre><code>. We would love to hear your findings regarding this method. :)

  3. Jeff Starr

    My pleasure! Thanks for the positive feedback ;)

  4. TechJammer 2007/10/24 12:18 pm

    Simple, and easy to understand, even for ME!! I’ve been getting spammed from lots of people adding ridiculous off-topic comments (usually selling something) on my site… This should help me screen them out!

    Thanks for the tip!!

  5. Sorry about that here is what I am using

    if(in_array($_SERVER['REMOTE_ADDR'],$bannedIP)) {
         // this is for exact matches
         header("Location: {$registry['bannedRedirect']}");
         exit();
    } else {
         // this is for wild card matches
         foreach($bannedIP as $ip) {
              if(eregi($ip,$_SERVER['REMOTE_ADDR'])) {
                   header("Location: {$registry['bannedRedirect']}");
                   exit();
              }
         }
    }

  6. Jeff Starr
    Perishable 2007/12/29 8:31 am

    Thank you for reposting, JRSofty! I will definitely be experimenting with this method and I am quite sure that it will help people who are dealing with wildcards. Thanks again for sharing your technique with us ;)

  7. If you get the warning that you can’t “modify header information” you can solve this by putting

    <?php ob_start; ?>

    at the very top of your page.

  8. Jeff Starr
    Perishable 2008/02/03 2:30 pm

    Thanks for reminding us of that, Alex — it is definitely helpful! (Note: I repaired the code in your original comment and deleted the corrective follow-up) – Cheers!

  9. Hello,
    I block IPs with this php-code:

    <?php $ips = array('123.456.7.8','123.456.7.9');
    if(in_array($_SERVER['REMOTE_ADDR'],$ips)) die( 'Access denied - Zugriff verweigert' ) ; ?>

    How can I block a full IP-Range with this Script? From 123.45.6.7 to 123.56.8.9?

  10. Jeff Starr
    Perishable 2008/02/09 8:03 pm

    Hi Fabian,
    Check out JRSofty’s comment and use wildcard operators to block the specified IP range. List all specific and/or address blocks in an array and test accordingly. ;)

  11. Cool. Thanks! It works fine.
    But how can I build in an e-mail notify or a log-file?

  12. Jeff Starr
    Perishable 2008/02/17 8:56 am

    Fabian, I am sure there are many ways to accomplish your scripting goals. I would recommend a good book on PHP or maybe even a Google search..

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
Today my trusty scanner died. Not going to replace it. And when my printer finally dies, I'm not going to replace that either.
Spent about a week or so away from screens and media as much as possible. Helps to regain perspective.
Celebrating 8 years providing premium WordPress plugins at Plugin Planet!
Power is *not* relying on a 3rd-party service to handle your email.
Streamlining my entire digital universe into a single highly focused beam.
Simply Static is my go-to plugin for generating static HTML versions of WordPress sites. Works flawlessly.
Note to self: never, ever, ever buy any CD or DVD from eBay. Every single time the discs are scratched, damaged, missing, fake, or worse. Never again you clowns.
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.