Skip to content

Instantly share code, notes, and snippets.

@lemmon
Created September 13, 2012 12:15
Show Gist options
  • Save lemmon/3713945 to your computer and use it in GitHub Desktop.
Save lemmon/3713945 to your computer and use it in GitHub Desktop.
Country Services
// get country code of site visitor
function getByVisitor()
{
if (array_key_exists( '__COUNTRY__', $_SESSION ))
{
return $_SESSION[ '__COUNTRY__' ];
}
elseif ($host=gethostbyaddr(Application::getIP()) and substr($host, -3, 1)=='.' and $country=substr($host, -2) and $country=Countries::make()->findLike('code', $country)->first()->code)
{
return $_SESSION[ '__COUNTRY__' ]=$country;
}
elseif ($country=self::fetchByIp(Application::getIp()) and $country!='XX')
{
return $_SESSION[ '__COUNTRY__' ]=$country;
}
else
{
return $_SESSION[ '__COUNTRY__' ]=null;
}
}
// remote country fetch by IP address of visitor
function fetchByIp($ip)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, 'http://api.hostip.info/country.php?ip=' . $ip);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
$country = curl_exec($ch);
curl_close($ch);
return $country;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment