Jun 10 2009

Match An IP Address To A Physical Location With PHP

Sometimes it’s useful to locate where a certain IP address is located. Usually this isn’t really that accurate but at least it gives you a general idea for stats or marketing research. I’ve written a simple php function that uses curl to query a IP address location database for the location info. In the function I specify that I want a JSON data structure containing the location information. I chose JSON over the XML alternative just for ease of use. The object that we get returned needs to be referenced in a specific kind of way. I show how under the function.
This function uses the IPInfoDB JSON php API. There are quite a few alternatives out there so feel free to do your research. The IPInfoDB PHP API returns :

  • Country Code (CA or US)
  • Country Name (Canada)
  • Region Code
  • Region Name (Province or Dtate)
  • City
  • Postalcode or Zip Code (which doesn’t always work)
  • Latitude
  • Longitude
  • gmt offset
  • Dst offset


function get_location_info($ip_address)
{
  $url = 'http://ipinfodb.com/ip_query.php?ip=';
  $url .= $ip_address;
        $url .= '&output=json';
  $ch = curl_init();
  
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
  $json_packet = curl_exec($ch);
  $location_array = json_decode($json_packet);
  curl_close($ch);
  return($location_array);

}//get_location_info

$loc_arr = get_location_info("69.157.107.64");
echo "\n";
echo $loc_arr->{'City'};
echo "\n";
echo $loc_arr->{'RegionName'};
echo "\n";
echo $loc_arr->{'CountryCode'};

Hopefully theres no confusion there.

Share