24 December 2013

Find Country Name By IP Address in PHP

This function will help you to find country from IP address...
Function will return country name and city name using the www.geoplugin.net service...

function getLocationInfoByIp()
{
 $client_ip  = @$_SERVER['HTTP_CLIENT_IP'];
 $forward_ip = @$_SERVER['HTTP_X_FORWARDED_FOR'];
 $remote_ip  = @$_SERVER['REMOTE_ADDR'];
 $return_data  = array('country'=>'', 'city'=>'');
 if(filter_var($client_ip, FILTER_VALIDATE_IP))
 {
  $ip_addr = $client_ip;
 }
 elseif(filter_var($forward_ip, FILTER_VALIDATE_IP))
 {
  $ip_addr = $forward_ip;
 }
 else
 {
  $ip_addr = $remote_ip;
 }
 $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip_addr));
 if($ip_data && $ip_data->geoplugin_countryName != null)
 {
  $return_data['country'] = $ip_data->geoplugin_countryCode;
  $return_data['city'] = $ip_data->geoplugin_city;
 }
 return $return_data;
}

No comments:

Post a Comment