January 2, 2009
PHP to redirect IP addresses to different page
By Martyn in PHP, Programming | 2 comments
If you would like to redirect browsers based on their IP the following method can be used to handle multiple IP’s. You can choose to redirect entire networks or a single ip.
<?php //array of ip's you wish to block. Note that you can block an //entire class by replacing it with 0, so to block a class c //(254 computers) use something like 123.123.123.0 $blockIP = array('123.123.123.0','100.100.100.101'); $remote = explode('.',$_SERVER['REMOTE_ADDR']); foreach($blockIP as $ip) { $goodIP = false; for($i=0;$i<4;$i++) { $ipSeg = explode('.',$ip); if($remote[$i] == $ipSeg[$i] || $ipSeg[$i] == '0') { //segment qualifies $goodIP = true; } else { //ip no good so move to the next $goodIP = false; continue 2; } } if($goodIP) { //ip passes so no need to check the rest $blockThisIP = $ip; break; } } //for convenience test $blockThisIP and process here //replace www.crayola.com with the place you wish to //send ip's too if($blockThisIP) { //php header method - can only use this if the page //has not begin to display in the browser header('Location: http://www.crayola.com'); //javascript redirection - use this method if browser has //begun to display page echo "<script type=\"text/javascript\"> window.location = \"http://www.crayola.com\";</script>"; } ?>
email this | tag this | digg this | trackback | comment RSS feed
AJ | Jan 6, 2009 | Reply
just wanted to say, a great little script, and Ive used it one one of my sites. Its for those that refund a product, so I can match their IPs, to restrict them from going to the membership area. Works great!
As my site is on a Windows server, an .htaccess file wasnt an easy option. Thanks again for a great little script. I will link back to your site in return.
AJ
Stefano | Nov 16, 2009 | Reply
Great .php script.
Thanks.
Stefano