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 = Web Developer. Security Specialist. WordPress Buff.
BBQ Pro: The fastest firewall to protect your WordPress.

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. 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. 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. 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. 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. 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. 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 »
The Tao of WordPress: Master the art of WordPress.
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.