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>";
}
?>
Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • Live
  • MySpace
  • PDF
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter
  • Yahoo! Buzz
  • Add to favorites

Tags:

One Comment to “PHP to redirect IP addresses to different page”

  1. AJ says:

    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

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">