Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
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.
The Tao of WordPress: Master the art of WordPress.

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

  1. Many Thanks

    we had some problem scrapers that were causing us some bandwidth problems… script did the trick thanks

  2. Perishable 2007/07/22 3:18 pm

    Glad to help, Scott — thanks for the feedback!

  3. We had a customer site DOS attacked by the old webmaster when he was fired. Being able to ban his IP so easily was a god send.

  4. Perishable 2007/09/08 1:06 pm

    Great, Kym!
    That is good news, indeed ;)
    Thank you for the feedback!

  5. The full IP address works with this script, but wildcards don’t seem to catch the addresses.

  6. Perishable 2007/09/16 9:30 am

    Trav,

    Try using this format instead:

    $deny = array("111.111..*..*", "222.222..*..*");

    i.e, using two dots before each wildcard operator should do the trick..

  7. August Klotz 2007/09/16 4:09 pm

    You can also use something similar to this:

    <? $block = "^123\.123\.";
    if (in_array($_SERVER['REMOTE_ADDR'],$block)) {
          header("HTTP/1.1 403 Forbidden");
          exit;
    } else {
          echo '<h1>Welcome to the site..</h1>';
    } ?>

    ..which would block any IP addresses beginning with 123.123. This code should also work without the second escaped dot (\.) in the first line. The caret (^) indicates the beginning of the string, while the dots are escaped for clarity.

  8. Thanks to both of you for those snippets. I kow very little php and have a hard time learning it so I appreciate it.

  9. Dead Letter Art 2007/09/17 11:45 am

    We use something along these lines to block specifically defined ranges of IP addresses:

    $hulkSmash = array ("^123.(12[3-9]|1[3-9][0-9]).","^321.321.(32[1-9]|3[3-9][0-9]).");
    foreach($hulkSmash as $smashed) {
       if (ereg($smashed, $_SERVER['REMOTE_ADDR'])) {
          echo "Sorry, but this site is not available..";
          exit();
       } else {
          echo "Welcome to our site, oh special ones..";
          exit();
       }
    }

    I agree with August that using a caret to denote the beginning of a string is a great approach — prevents false positives, etc.

  10. This PHP code doesn’t work for an array of IP addresses. I tried several times but none of the above techniques work! They only work if you know the complete IP address (i.e. xxx.yyy.zzz.aaa). Any clue on how to get this thing to work on an entire range? Thanks!

  11. i like this web because you can discover how to unblock some web. i want to know What is the code 222.22.222.

  12. Ok, I’m new at PHP and this looks cool but what I want to do is allow all our IP’s access and if they don’t match then no access.
    We have a lot of them (large gov’t agency).
    So I’d want something like all
    123.123.*.*
    123.12.*.*
    124.13.*.*
    and then some
    123.123.123.*
    321.123.223.*
    etc.
    to get in ok.

    Ideas?

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 »
SAC Pro: Unlimited chats.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.