Skip to content

Instantly share code, notes, and snippets.

@steinbring
Last active August 29, 2015 14:06
Show Gist options
  • Save steinbring/28c2020c80ce89045c26 to your computer and use it in GitHub Desktop.
Save steinbring/28c2020c80ce89045c26 to your computer and use it in GitHub Desktop.
This gets the user's location, via their IP address. If the user's IP address is reported as being in an internal range, it does an additional query for their public IP (This is mainly just useful in a development scenario).
<?php
function get_public_ip_address()
{
// SOURCE: https://github.com/dotancohen/utility-functions/blob/master/ip-addresses.php
$url="simplesniff.com/ip";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function getCountryByIP()
{
// Is REMOTE_ADDR there and is it not a '10.' address
if(isset($_SERVER['REMOTE_ADDR']) && substr($_SERVER['REMOTE_ADDR'],0,3) != '10.'){
// Use their reported IP
$ipAdd = trim($_SERVER['REMOTE_ADDR']);
}else{
// Use a third-party to get the user's public IP
$ipAdd = trim(get_public_ip_address());
}
$LocationData = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$ipAdd"));
return $LocationData['geoplugin_countryName'];
}
echo getCountryByIP();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment