Skip to content

Instantly share code, notes, and snippets.

@susanBuck
Created June 1, 2012 08:08
Show Gist options
  • Save susanBuck/2850172 to your computer and use it in GitHub Desktop.
Save susanBuck/2850172 to your computer and use it in GitHub Desktop.
geolocation
function locate() {
// first try to use geoIP library for IP address, since it uses it's own IP detection
$ip = $_SERVER['GEOIP_ADDR'];
if (empty($ip))
$ip = self::ip_address();
// if we're on the localhost inject an IP address
if ($_SERVER["SERVER_NAME"] == "localhost")
$ip = "76.109.14.196"; // Miami, FL
// $ip = "24.44.58.79"; # Connecticut
// $ip = "78.86.225.25"; # Great Britain
// If we want to mimick being a foreign country we can create an IP cookie
$ip = ! empty($_COOKIE["IP"]) ? $_COOKIE["IP"] : $ip;
// default values (if nothing is found)
$geo = array();
$geo['ip'] = $ip;
$geo['country_code'] = 'US';
$geo['state'] = NULL;
// use geoip library if available
$record = (is_callable('geoip_record_by_name')) ? geoip_record_by_name($ip) : array();
// use found values
if (! empty($record))
$geo = array_merge($geo, $record);
// debug info
echo '<!-- Geolocation: '.print_r($geo, TRUE).' -->';
return $geo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment