Monthly Archives: January 2009

PHP to redirect IP addresses to different page

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>";
}
?>