How to Block IP Addresses with PHP
by Jeff Starr on Tuesday, July 3, 2007 – 85 Responses
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 relatively 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: http://www.google.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, quietly, and without any fuss.
Thus, 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., *). After editing the array of IP addresses, upload the file to your server and relax. 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. If you customize, remember to change the redirect URL (i.e., http://www.google.com/) to that of your custom page.
Focused on clean code and quality content, Perishable Press is the online home of Jeff Starr, author, artist, designer, developer, and all-around swell guy. 





85 Responses
Add a comment
Scott – #1
Many Thanks
we had some problem scrapers that were causing us some bandwidth problems… script did the trick thanks
Perishable – #2
Glad to help, Scott — thanks for the feedback!
Kym – #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.
Perishable – #4
Great, Kym!
That is good news, indeed ;)
Thank you for the feedback!
Trav – #5
The full IP address works with this script, but wildcards don’t seem to catch the addresses.
Perishable – #6
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..
August Klotz – #7
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.Trav – #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.
Dead Letter Art – #9
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.
j – #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!Robert – #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.rick – #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?
JRSofty – #13
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 theeregi()function and check each item in your array separately for example:[ Editor’s note: code example gobbled by WordPress ]
Perishable – #14
JRSofty,
Please repost! Your code example was gobbled up by WordPress.. Either wrap each line in
<code>tags or enclose the whole lot in a<pre>element. We would love to hear your findings regarding this method. :)TechJammer – #15
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!!
Perishable – #16
My pleasure! Thanks for the positive feedback ;)
JRSofty – #17
Sorry about that here is what I am using
if(in_array($_SERVER['REMOTE_ADDR'],$bannedIP)) {// this is for exact matchesheader("Location: {$registry['bannedRedirect']}");exit();} else {// this is for wild card matchesforeach($bannedIP as $ip) {if(eregi($ip,$_SERVER['REMOTE_ADDR'])) {header("Location: {$registry['bannedRedirect']}");exit();}}}Perishable – #18
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 ;)
Alex – #19
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.
Perishable – #20
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!
Fabian – #21
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?
Perishable – #22
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. ;)
Fabian – #23
Cool. Thanks! It works fine.
But how can I build in an e-mail notify or a log-file?
Perishable – #24
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..
Andy – #25
Thanks for a neat little script. This is the second solution I’ve found on Perishable Press in as many months. Way to go :-)
Perishable – #26
Excellent, Andy — thanks for the feedback! :)
Nelson – #27
thanks a lot for this great script
i’ve searched mor then 2 h for one thing like this and finally gotted
THANKS
Perishable – #28
My pleasure, Nelson — glad to be of service! :)
Nelson – #29
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
Perishable – #30
Hi Nelson, check out JRSofty’s technique for more information on using wildcard operators via PHP.
Nelson – #31
sorry but i didnt understad the JRSoft
(i’m new at this php language and all this kind of stuff) just starting :)
stealth – #32
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,allowErrorDocument 403 /errordocs/403.phpdeny from 123.123.123.123deny from 234.456.deny from aol.comdeny from cox.netPerishable – #33
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.
Mike – #34
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?
Perishable – #35
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.phpfile that serves as your home page. To implement this technique, you would open theindex.phpfile 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.Just Jen – #36
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!
Jeff Starr – #37
Hi Jen, I understand your frustration; as far as I know, blogspot doesn’t provide access to the “under-the-hood” mechanics of your site. Unfortunately, that leaves you with only the tools they provide, which may prove inefficient for long-term blog operation. For example, you might be able to require registration before anyone can visit your site. If so, there goes 90% of your traffic. Also, it is easy for anyone (stalker or not) to sign up for a fake account and then you’re back where you started, only with much less traffic..
As for switching to a site that provides access to PHP, htaccess, and other powerful tools, I don’t think there any free hosted sites that offer such luxury. There is Blogger, WordPress, Facebook, MySpace, and all of those places, but I am pretty sure that you would be in the same boat as with Blogspot.
Unfortunately, having control over the “behind-the-scenes” functionality of a website generally requires a self-hosted solution: i.e., domain name, web host, installing your own blog platform — the whole bit. This either requires a lot of time learning the ropes or a lot of money to have someone do it for you.
I hope this was useful for you — Good luck! :)
Just Jen – #38
Thank you for filling me in :)
I’m going to close down blogger…sigh…but I found my blogstalkers through statscounter so I can keep a better eye out at a different site. Unfortunately it is quite an undertaking to notify everyone but feel this is the only way. I am lucky in the fact its not my business site which is on its own domain, I guess I will have to do the same with a blog if I want to keep that hobby :)
Thanks again for trying :D
Jeff Starr – #39
No problem, Jen — I wish there was more I could do.. Let me know if you get setup with your own blog; I have all sorts of lovely tricks up my sleeve for stopping stalkers, spammers, and other scumbags ;)
Regards,
Jeff
Just Jen – #40
LOL
I know you do! I’ve checked out this blog and don’t worry, I’ll be back :)
My blog is presently closed until Friday where my last post will be up confronting my blogstalker and then the blog will be deleted on tues aug 26. It should be interesting, if you wanted to swing by and see a live blog soap opera this weekend then please do so ;)
Jeff Starr – #41
I would love to watch the action! Do I need an invite to get in?
Just Jen – #42
lol
no invite…it’ll be posted on friday morning and then I’ll set my blog to ‘everyone’. It was set for everyone until my blogstalker stepped over ‘my line’ of patience yesterday…lol…shut it down to think on things. So on friday it’ll be open.
Jeff Starr – #43
Oh, I am SO there on Friday ;)
Just Jen – #44
http://humbleopinion2.blogspot.com/2008/08/sigh.html
my last post
the soap opera, episode 1 has begun…bwahahaha (thats my evil laugh…I know, it needs work…lol)
Mike H – #45
for those that use blog spot this could help I had to put it in my wife’s blog do to someone making nasty comments.
http://toolator.com
use to be 'just jen'...shsh..stealth mode – #46
For the record, I tried toolator and it only worked for a few days. When the blogstalker’s IP changed, I couldn’t get back in to change the IP at toolator. Nor could add any other webpage or anything…so if this happens to her and you find a way around it, let me know, I’ll add it to my new blog
thanks
Jeff Starr – #47
Jen, you are hilarious! How did everything go with that last post? I am just getting back from a nice vacation and have been away from the computer and out of the loop..
use to be 'just jen'...shsh..stealth mode – #48
nice…vacation…lol
it was fine, she realized I could track her (to the point my hubby could leave messages on her comp…lol)and knew who she was so she got other people to track my blog for her…then I closed it down and started new…so far so good…just don’t call me jen over at this new one and she’ll never find me…blogland is a small world…lol
Jeff Starr – #49
Sounds good, Jen. Glad to hear everything is back on track with your new blog. Hopefully your stalker will give up looking for you and move on with her life. Best of luck to you; let me know if I may be of any help in the future. :)
Cheers,
Jeff
use to be 'just jen'...shsh..stealth mode – #50
Thanks for the well wishes :)
you can stop by and visit my blog any time you want but don’t expect anything too exciting…LOL
Keep me posted on that toolator :)
David – #51
Hi Jeff, Could you help me out with some code that will block an IP on a Craigslist ad? Please? Someone is deleting my ad every day. I have their IP address, but can’t find a code that will work. Please help if you can. Thanks, David
Jeff Starr – #52
Hi David, I feel your pain, but unfortunately blocking someone from accessing the Craigslist site requires access to the Craigslist server, unless I am missing something here..
David – #53
Thanks Jeff. I was ready for that answer. Do you, or does anyone have any neat little tricks that I can add to the html of the ad to get a little pay back?
Jeff Starr – #54
Unfortunately, all of the fun stuff requires access to the server.. And even then, getting involved with “pay back”-type behavior may be risky, especially if you aren’t really familiar with what you are doing. The person whom you are targeting might be some deadly hacker ninja who could ruin your life. Not worth it, in my opinion.
Szektor – #55
Hi,
this is a nice code.
Do you know about a free hacker/spammer ip database?
That is the only thing I miss now. ;)
Jeff Starr – #56
Yes, that would be nice, eh! ;)
John Boyd – #57
Thanks for the post. Do you know how to deny a submission if keywords and .com etc. are in the message field?
John Boyd – #58
P.S.
Here’s a cool link to redirect them to rather than google: http://www.ftc.gov/bcp/conline/edcams/spam/report.html
: )
Cemal – #59
I am trying to prevent a spam source from leaving comments or pingbacks. Although spam is caught by Akismet it clutters my mind more than anything else. I placed this snippet at the very top of the header.php file with no effect what so ever. Am I supposed to place it after the DTD declaration or HTML or any other part?
Thank you.
Cemal
Jeff Starr – #60
Hi Cemal, the problem is that comments and pingbacks are processed by a file other than those found in your WordPress theme files. The theme files display information from the database, but they aren’t generally involved in putting it there. Instead, look for a file called
wp-comments.php(or something similar, depending on your particular WP version), and try adding the code to that file. Thewp-comments.phpis the actual file that must be accessed by commentators (or spammers, etc.) to leave comments. Placing the PHP block script at the very beginning of that file should do the trick, although I have not tested it because I prefer to block via htaccess instead.Regards,
Jeff
Cemal – #61
Jeff, thank you very much for the quick response. I added an htaccess file but it did not have any effect either. It may be because my site is running on Windows IIS platform. I will try your suggestion and let you know.
Thanks agin,
Cemal
Cemal – #62
Well, I placed the code snippet into three files:
wp-blog-header.php
wp-comments-post.php
wp-trackback.php
The first one seemed to be the header for all the files, so there it went. The other two by virtue of their names received the same treatment. The code snippet I inserted is below (I hope it does not get gobbled up):
After this, the code that was there starts, again with <?php and so on.
The spammers are still able to post, not visible but they are not blocked. What am I doing wrong? Am I supposed to take the part that begins with $deny and ends with exit(); and place it inside the original code? I know as much about php as I know how to jump over tall buildings!
If this is too much, I certainly can keep deleting the posts. I don’t mean to be bugging you.
Thanks,
Cemal
Jeff Starr – #63
@Cemal: If the goal is to prevent spam from reaching your post comments, there may be no need to fiddle around with PHP, htaccess, and other intrusive methods of protection. Fortunately, there are several excellent WordPress plugins that do an excellent job preventing and eliminating comment spam, among which are Akismet, Bad Behavior, and Spam Karma. Check these out and see if any suit your needs; if not, try searching for alternates on Google — there should be several.
Regards,
Jeff
kristy – #64
Hi I want to write a script to block some ip address on my
index.phpi have tried the script above.
it only block when i type
domain.comas my urlbut it will not block when i type in
www.domain.comanyone know why? and how can i rewrite the script to block
www.domain.comtoo?here is the script i used:
$deny = array("11.111.1.1");if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) {echo " exit please";exit();Jeff Starr – #65
@kristy: this sounds like a canonicalization issue. Your best bet is to get all URL requests resolving to either
wwwor non-wwwversions of your pages. This should not only remedy the IP-blocking script, but also improve the overall SEO-quality of your site as well.Tomi Teirikangas – #66
I have a huge problem i have blocked like 40 ip addresses, always who is spamming to my website, is changing ip address, how i make him stop, soon ill go his home and rip his computer out of the wall and throw it out of the window
Greetings from finland, ITS FREEZING HERE
Jeff Starr – #67
@Tomi Teirikangas: I feel your pain! Unfortunately, if someone wants to spam your site bad enough, there is really no way of stopping them from doing so. You can target different aspects of the spam attacks, however. For example, instead of blocking via IP, you may check to see if he using the same user agent and then block that instead (or in addition to). Likewise, if he is always spamming you using the same keywords or phrases, you could use some regex magic and block them as well. It really all depends on your setup and the nature of the attacks. I recently went into great depth explaining several strategies for preventing spam and malicious activity; you can read through the articles that are summarized here for more information on this topic.
You could also physically destroy his machine, but it sounds like you might prefer to stay indoors where it’s warm ;)
Tomi Teirikangas – #68
HAAA i god it i make him stop like you Jeff said, got an idea form this sentence “if he is always spamming you using the same keywords or phrases”, now i have blocked 3 links what he pasted to my site, no there hasn’t been any spams, last night was clean :D thanks for all help Jeff.
PHP <3
kristy – #69
hey jeff,
so where should i start? do you have any link that can show me how to solve the canonicalization issue ?
thanks,
Jeff Starr – #70
Hi kristy, here is an article I wrote on Universal www-Canonicalization via htaccess. It has everything you need to resolve essential canonicalization issues for your site.
Sandy – #71
Jeff,
I am 70 years old and not very computer savvy. I want to thank you for the list of IPs to block when they come up. I was never quite sure when they mention they are trying to connect with remote IP #…..so, I always select “block” to be safe. Thank you for your help and I will keep your site in my “favorites” for reference and to learn.
Sandy
Jeff Starr – #72
@Sandy: Thank you for the positive feedback — it is my great pleasure to provide assistance to the community! Cheers! :)
Jack – #73
Thanks Jeff.. I never knew its so simple to kick spammers :)
Dave – #74
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
Dave – #75
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
Jeff Starr – #76
@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
Ayumi – #77
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)
Sms India – #78
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 ???
Jeff Starr – #79
@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.
Brad – #80
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.
Jeff Starr – #81
@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.
Chris – #82
Hi, The script for some reason didn’t work :(
Would you be able to help ?
Thanks,
Chris :-)
Trackbacks / Pingbacks