Skip to content

Instantly share code, notes, and snippets.

@saroarhossain57
Created December 31, 2023 18:54
Show Gist options
  • Save saroarhossain57/8f2582125d2b44154d8124fa730fbadb to your computer and use it in GitHub Desktop.
Save saroarhossain57/8f2582125d2b44154d8124fa730fbadb to your computer and use it in GitHub Desktop.
Get visitor location data PHP
function get_ip_location(){
$client_ip = @$_SERVER['HTTP_CLIENT_IP'];
$forward_ip = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote_ip = @$_SERVER['REMOTE_ADDR'];
$result = array('country_code'=>'', 'country_name'=>'', 'region'=>'', 'city'=>'');
if(filter_var($client_ip, FILTER_VALIDATE_IP)){
$ip_address = $client_ip;
} elseif(filter_var($forward_ip, FILTER_VALIDATE_IP)){
$ip_address = $forward_ip;
} else{
$ip_address = $remote_ip;
}
$loc_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip_address));
if($loc_data && $loc_data->geoplugin_countryName != null){
$result['country_code'] = $loc_data->geoplugin_countryCode;
$result['country_name'] = $loc_data->geoplugin_countryName;
$result['region'] = $loc_data->geoplugin_region;
$result['city'] = $loc_data->geoplugin_city;
} else{
$result['country_code'] = 'US';
$result['country_name'] = 'United State';
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment