Skip to content

Instantly share code, notes, and snippets.

@borzov
Created May 12, 2013 06:07
Show Gist options
  • Save borzov/5562600 to your computer and use it in GitHub Desktop.
Save borzov/5562600 to your computer and use it in GitHub Desktop.
PHP: Determination of the country by IP
function get_country($ip_addr) {
$curlopt_useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0';
$url = 'http://www.geoplugin.net/php.gp?ip=' . $ip_addr;
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch1);
$geoplugin = unserialize($result);
if ($geoplugin[geoplugin_countryCode] != '') {
return $geoplugin[geoplugin_countryCode];
} else {
$url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip_addr);
$ch = curl_init();
$curl_opt = array(
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $curlopt_useragent,
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => 1,
CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
);
curl_setopt_array($ch, $curl_opt);
$content = curl_exec($ch);
if (!is_null($curl_info)) {
$curl_info = curl_getinfo($ch);
}
curl_close($ch);
if (preg_match('{<li>Country : ([^<]*)}i', $content, $regs))
$country = $regs[1];
return $country;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment