Skip to content

Instantly share code, notes, and snippets.

@guoxiangke
Created September 7, 2015 07:46
Show Gist options
  • Save guoxiangke/94e8124c6be579b8b1c9 to your computer and use it in GitHub Desktop.
Save guoxiangke/94e8124c6be579b8b1c9 to your computer and use it in GitHub Desktop.
Geolocation maxmind
/**
* Geolocation
*/
$ip = $_SERVER['REMOTE_ADDR'];
$result = db_select('ip_geolocation', 'g')
->fields('g')
->condition('ip', $ip, '=')
->execute()
->fetchAssoc();
$state = 'IL';
if ($result) {
$state = $result['state'];
} else {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://geoip.maxmind.com/geoip/v2.0/city_isp_org/'.$ip);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_USERPWD, '90277:nnrc6BtnK0fB');
$result = curl_exec($curl);
curl_close($curl);
$result = json_decode($result);
if (!isset($result->error) && isset($result->subdivisions) && count($result->subdivisions) > 0 && isset($result->subdivisions[0]->iso_code)) {
$state = $result->subdivisions[0]->iso_code;
//Save state
db_insert('ip_geolocation')
->fields(array(
'ip' => $ip,
'state' => $result->subdivisions[0]->iso_code
))
->execute();
}
}
/**
* End Geolocation
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment