Just a function to get geographical info about an IP.
I use this actually to stop spammers from certain countries…I know a bit to radical, but after using IP (of banned lists), captchas, akismet, banned names etc…I don’t know what else to do :S. (it seems is already working no spam in 1 week)
Usage:
$geoip=geoIP('81.60.189.183');//using an existing IP
$geoip=geoIP();//will use clients IP
print_r($geoip);
echo $geoip['country'];
echo $geoip['countryAb'];
echo $geoip['city'];
if ($geoip['country']=='india') die('country not allowed');//to ban a country
The code:
function get_tag($tag,$xml){
preg_match_all('/<'.$tag.'>(.*)'.$tag.'>$/imU',$xml,$match);
return $match[1];
}
function valid_ip($ip){
return ( ! preg_match( "/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/", $ip)) ? FALSE : TRUE;
}
function geoIP($stringIp=-1){
if (!valid_ip($stringIp)) $stringIp = $_SERVER['REMOTE_ADDR'];
if ($_COOKIE['geoip']){
$geoip=unserialize($_COOKIE['geoip']);
if ($geoip['ip']==$stringIp) return $geoip;//only return if IP is the same if not continue
}
$url='http://api.hostip.info/?ip='.$stringIp;// Making an API call to Hostip:
$xml = file_get_contents($url);//echo $url;
$city = get_tag('gml:name',$xml);
$city = strtolower ($city[1]);
$countryName = get_tag('countryName',$xml);
$countryName = strtolower ($countryName[0]);
$countryAbbrev = get_tag('countryAbbrev',$xml);
$countryAbbrev = strtolower ($countryAbbrev[0]);
$geoip['ip']=$stringIp;
$geoip['city']=$city;
$geoip['country']=$countryName;
$geoip['countryAb']=$countryAbbrev;
setcookie('geoip',serialize($geoip), time()+60*60*24*14);// Setting a cookie with the data, which is set to expire in 2 weeks:
return $geoip;
}