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.
BBQ Pro: The fastest firewall to protect your WordPress.

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

  1. Thanks for a neat little script. This is the second solution I’ve found on Perishable Press in as many months. Way to go :-)

  2. Perishable 2008/04/27 8:54 am

    Excellent, Andy — thanks for the feedback! :)

  3. thanks a lot for this great script

    i’ve searched mor then 2 h for one thing like this and finally gotted

    THANKS

  4. Perishable 2008/06/23 3:13 pm

    My pleasure, Nelson — glad to be of service! :)

  5. i’m with a problem…
    my IP
    62.139.181.17

    if i put only
    “62.*”,
    i still can get inside the page.
    How can it works only using 2 or 3 numbers from the first ones of the IP’s adress?
    i would like to have something like:
    “62.*”,
    “63.*”,
    “64.*”,

    thanks

  6. Perishable 2008/06/23 4:22 pm

    Hi Nelson, check out JRSofty’s technique for more information on using wildcard operators via PHP.

  7. sorry but i didnt understad the JRSoft

    (i’m new at this php language and all this kind of stuff) just starting :)

  8. Nice script. I use a similar php script using $ip = $_SERVER[‘REMOTE_ADDR’]; to log the ip addresses of visitors to my site and then output those ip’s, time, and date to a text file. I then have another script that then logs and writes any future attempts from those banned ips to an errordocs directory. So for the nasty ip’s, ranges, domains I really want banned i don’t even fool with any scripts – i just simply use the “brute force” method of an .htaccess file like below. I also make it a point to add the known ranges of most proxies to prevent them from attempting to connect via a web proxy site. You can ban exact ip’s, ranges, isp’s, or just only the lower level domains under an ISP. Just place the .htaccess file on the root of your site with the contents similar to below as below. The aol.com and cox.net were simply graphic examples of the filtering power of an .htaccess file. You can also comment out the errordocs line if you don’t want to redirect them to your own custom page.

    order deny,allow
    ErrorDocument 403 /errordocs/403.php

    deny from 123.123.123.123
    deny from 234.456.
    deny from aol.com
    deny from cox.net

  9. Excellent information, stealth. Blocking individual agents, IPs, and domains is a great method for specific cases, but for long-term scalability it is not as practical. I recently posted a series of articles discussing this and other aspects of the blacklist strategy as a viable security method. The series concludes with a “3G” blacklist that targets the most common aspects of attempted exploits and attacks. By focusing on and protecting against potential attack vectors, we avoid insane user-agent and IP blacklists while preventing a vast majority of exploit attempts.

  10. Hello, I’m enjoying your page very much. Please forgive me for being less talented in this area however, in reading one of your posts from the first page, I’m wondering where one type’s such things such as your example here:

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

    Is this done in the command window?

  11. Perishable 2008/07/13 7:43 am

    Hi Mike, if I understand you correctly, you are wondering where to place the code that is provided in the article. First of all, this article assumes that you are using PHP to deliver site content. For example, you might have an index.php file that serves as your home page. To implement this technique, you would open the index.php file and paste the code at the very top of the document. Edit the IP address to match the one that you would like to block. Then save the file and upload it to your server. If all goes according to plan, the IP address specified in the code will not be able to access your site.

  12. I’m up the creek here. I’ve read everything on this page and somewhat understand (I’m not ditsy but I sure am when it comes to this stuff…lol) I have blogspot and it runs on xhtml…does this code work in that? If not, could you recommend a site that I could use a blog and be able to use this code to block? Or anything to block? I have a stalker and she’s threatening me now…sigh…I’m desperate but have no clue what to do! I’ll be back in hopes of answer :)
    I’m willing to change sites but there’s no point if my stalker is just going to hunt me down (btdt) and I’m not tech savvy, have no clue the difference between wildcard and php and htpaccess and xhtml…sigh
    Thank you for you patience!

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 »
Blackhole Pro: Trap bad bots in a virtual black hole.
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.