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. Thanks Jeff.. I never knew its so simple to kick spammers :)

  2. I have a feedback form on my website that has been getting hit by spammers. I never understood why they would target a feedback form, but now after reading this thread it makes sense that they are probably just running a script that looks for anything that might possibly publish the spam onto the website and do not recognize the difference between a feedback form and a blog comment form.

    I started trying to log ip addresses using some code from above. It works well on all the legitimate messages that I’ve gotten so far, however I am not getting any IP address from the last two pieces of spam that came through. That’s easy enough to block by just blocking anything with an empty IP address. But I don’t want to miss any legitimate messages coming through our feedback form, so I’m not sure if there are legitimate circumstances when the above code would not be able to pull an IP address or would that only happen if someone is intentionally blocking the IP address? How might they be doing this?

    BTW great site, thanks!
    Dave

  3. Whoops – I found the problem with not getting IP addresses on the incoming spam. I had the IP logging code on the feedback form and posted it to the actual submit page. So the spammers are apparently bypassing my form and just directly passing the data to my submit page. Anyhow the fact that they skip the form should be a pretty good way to identify the spam from the legit messages.

    Dave

  4. @Dave: Absolutely. To prevent this from happening on WordPress-powered sites, we simply use a little HTAccess to block all no-referrer requests. Perhaps something like this will work in your situation as well. Thanks for posting the follow-up comment, btw!
    Cheers, Jeff

  5. I have an IP I wish to block, but the IP is 220.255.7.177. But the three last numbers change quite frequently. Where should I place the wildcard operator? (Following your code)

  6. Hello, very nice website, but can you tell me one thing ?
    I want a script through which we can trace ip in a file.html or something ???

  7. @Ayumi: The script in the article has been found not to work well with wildcard operators. This was discussed in the comment thread beginning at around comment #13 by JRSofty. A little further down the thread, JRSofty provides a way to loop through the IP addresses that is better accommodating of wildcard operators.

    @Sms India: I’m not sure about that.. you may want to try searching on Google for more information.

  8. In keeping track of who lands on my site(other than googlebots and crawlers) I test the IP’s at the website http://www.stopforumspam.com first and if they show up as spammers they are entered into a database.

    As they show up on my site again I dont bother to send them anywheres else or redirect them, I simply check their IP against my spammer database then if positive I display a “nice note” showing their IP and then have the script die. The script runs at the top of all my pages as part of the template so no matter where they go they are blocked

    All they ever see of my site is the nice note I leave them. Of course I dont have a high traffic site so its no problem to keep them under review.

    I have thought of redirecting them back to their own IP. Wonder how that would work.

  9. Jeff Starr 2009/05/27 8:43 am

    @Brad: Very interesting approach, and definitely good grist for the mill. I would be concerned about performance on high-volume sites, but many targeted sites receive relatively low amounts of traffic.

    Also, thanks for the link to stopforumspam.com — another useful tool in the ongoing war on spam. Cheers.

  10. Hi, The script for some reason didn’t work :(

    Would you be able to help ?

    Thanks,
    Chris :-)

  11. Taniguchi, J.T. 2010/04/20 5:48 am

    Hi yall,

    I know the topic it’s kinda old but after reading the comments above, I decided to put it all together within a usable function:

    // First create a text file and add some dummy IPs
    [test.txt]
    �]u�]u�m��}��}��}�

    // Then copy and paste the following function into a php file:
    (change the $list var to your list address)
    (change the header() method to whatever you want)
    [block_ip.php]

    // Usage:
    �w%�כ��$��a��^rD�r��

    Hope it helps =)

    Editor’s note: It looks like the actual code got mangled during the submission process (or elsewhere). Note to anyone else reading this comment, please do not try using the gibberish as code, because it won’t work.

  12. Taniguchi, J.T. 2010/04/20 5:58 am

    wow, wordpress just eat the entire code.
    I post it on my blog too: http://www.phpseeker.org/viewtopic.php?f=7&t=1387

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
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.
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
Crazy that we’re almost halfway thru 2024.
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.