Skip to content

Instantly share code, notes, and snippets.

@neo22s
Created July 29, 2015 17:20
Show Gist options
  • Save neo22s/9a92448b1dbf3067ef3e to your computer and use it in GitHub Desktop.
Save neo22s/9a92448b1dbf3067ef3e to your computer and use it in GitHub Desktop.
Get ip geo info using 3rd party API's
die(print_r(ip_details("8.8.8.8")));
function ip_details($ip)
{
//list of providers to return IP information for free
$providers = array( 'ipinfo' => array('url' => "http://ipinfo.io/{$ip}/json",
'country_code' => 'country',
'country' => 'country',
'city' => 'city',
'region' => 'region',
'postal_code' => 'postal',
'lat' => 'loc', //"loc": "37.3860,-122.0838",
'lon' => 'loc'),
'ip-api' => array('url' => "http://ip-api.com/json/{$ip}",
'country_code' => 'countryCode',
'country' => 'country',
'city' => 'city',
'region' => 'regionName',
'postal_code' => 'zip',
'lat' => 'lat',
'lon' => 'lon'),
'telize' => array('url' => "http://www.telize.com/geoip/{$ip}",
'country_code' => 'country_code',
'country' => 'country',
'city' => 'city',
'region' => 'region',
'postal_code' => 'postal_code',
'lat' => 'latitude',
'lon' => 'longitude'),
);
//get 1 provider randomly
$provider = array_rand($providers);
$provider = $providers[$provider];
//get the info
$result = file_get_contents($provider['url']);
$result = json_decode($result);
//get lat and long in case are in the same ipinfo
if ($provider['lat'] == $provider['lon'])
{
$coords = explode(',',$result->$provider['lat']);
//die(var_dump($coords));
$lat = (float) $coords[0];
$lon = (float) $coords[1];
}
//normal
else
{
$lat = $result->$provider['lat'];
$lon = $result->$provider['lon'];
}
//return details
$details = array( 'country_code' => $result->$provider['country_code'],
'country' => $result->$provider['country'],
'city' => $result->$provider['city'],
'region' => $result->$provider['region'],
'postal_code' => $result->$provider['postal_code'],
'lat' => $lat,
'lon' => $lon);
return $details;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment