PHP GeoIP redirection.

This script uses the Maxmind GeoIP redirection which in this case is hosted by https://freegeoip.net which will return a XML with the details of the visitors IP.


<?php 

//Start session to avoid infinity loops
session_start();
// store session data
$_SESSION['geo']=1;


//Get the client country and set ip that not be redirected
$countriesrow = array('US','CA','AP','AR','BR','CN','CL','CO','CR','GT','HK','JP','KR','MX','SG','TH','TW'); //These are the countries that would be redirected to the normal site
$countrieseuro = array('AT','BE','BG','CH','CZ','DE','DK','EE','EG','ES','EU','FI','FR','GB','GR','HR','HU', 'IE','IL','IN','IS','IT','LU','LV','MA','MC','NL','NO','PL','PT','RO','RS','RU','SE','SI','SK','UA','ZA'); //This will be redirected to the eu version
$admin = '31.53.62.141'; //Put here your IP

//Get the client IP
$ipc =  $_SERVER['REMOTE_ADDR'];
$surl = "https://freegeoip.net/xml/".$ipc;

//Check if freegeoip is available
$response = get_headers($surl);
$response = $response[0];
if ($response == "HTTP/1.1 200 OK") {
	$avl = 1;
} else {
	$avl = 0;
}
if ($avl == 1){
$getxml = trim(file_get_contents($surl)); // get raw post data + trim out the spaces
$xmlsimp = new SimpleXMLElement($getxml);  // convert to object array
$ccode = $xmlsimp->CountryCode;  // returns the country code of the visitor example "US"
}
$country = $ccode;

//$xmlsimp->Ip; // returns the Ip address of the visitor
$gurl = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$gurl);
$cdir = $_SERVER['SERVER_NAME'];
for ($i = 0; $i < count($parts) - 1; $i++) {
 $cdir .= $parts[$i] . "/";
}

$urlParts = explode('.', $_SERVER['HTTP_HOST']);
$subdomain = $urlParts[0]; //or 0 if no www


if ($subdomain !== "eu" && in_array($country, $countrieseuro) && $_SESSION['geo'] == 1 &&  $avl == 1  && ($admin !== $ipc)) 
	{ header('Location: https://eu.rockandpebble.com' . $gurl . '');
	  exit;
	}
elseif ($subdomain !== "eu" && in_array($country, $countrieseuro) && $_SESSION['geo'] == 1 &&  $avl == 1 && ($admin !== $ipc))  
	{ 
		header('Location: https://rockandpebble.com' . $gurl . '');
	  exit;
	}
?>