Skip to content

Instantly share code, notes, and snippets.

@devluis
Created August 24, 2014 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save devluis/40b489d9c0de551dcaca to your computer and use it in GitHub Desktop.
Save devluis/40b489d9c0de551dcaca to your computer and use it in GitHub Desktop.
This simple function allows you to detect a country code and city of your site visitors, using the www.geoplugin.net service. You may use this data to add default values in registration form or use it for any other purposes, like blocking access to your site from special regions.
<?php
# Reference http://www.apphp.com/index.php?snippet=php-get-country-by-ip
function getLocationInfoByIp(){
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = @$_SERVER['REMOTE_ADDR'];
$result = array('country'=>'', 'city'=>'');
if(filter_var($client, FILTER_VALIDATE_IP)){
$ip = $client;
}elseif(filter_var($forward, FILTER_VALIDATE_IP)){
$ip = $forward;
}else{
$ip = $remote;
}
$ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
if($ip_data && $ip_data->geoplugin_countryName != null){
$result['country'] = $ip_data->geoplugin_countryCode;
$result['city'] = $ip_data->geoplugin_city;
}
return $result['city'];
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment