Skip to content

Instantly share code, notes, and snippets.

@sureshdsk
Last active March 25, 2019 15:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sureshdsk/86a069d6d8e9126b44c4 to your computer and use it in GitHub Desktop.
Save sureshdsk/86a069d6d8e9126b44c4 to your computer and use it in GitHub Desktop.
GeoLocation of an IP Address using PHP & Python
<?php
//Tutorial : http://www.idiotinside.com/2015/02/05/find-geolocation-of-an-ip-address-using-php-and-python/
$ipAddress = "IP_ADDRESS";
$ip_key = "YOUR_API_KEY";
$query = "http://api.ipinfodb.com/v3/ip-city/?key=" . $ip_key . "&ip=" . $ipAddress . "&format=json";
$json = file_get_contents($query);
$data = json_decode($json, true);
if ($data['statusCode'] == "OK") {
echo '<pre>';
echo "IP Address: " . $ipAddress;
echo "Country: " . $data['countryName'];
echo "Region: " . $data['regionName'];
echo "City: " . $data['cityName'];
echo "Latitude: " . $data['latitude'];
echo "Longitude: " . $data['longitude'];
echo '</pre>';
} else {
echo $data['statusCode']." ".$data['statusMessage'];
}
?>
#Tutorial : http://www.idiotinside.com/2015/02/05/find-geolocation-of-an-ip-address-using-php-and-python/
import urllib2
import json
def getIPAddress(api_key,ip_address):
api_endpoint = "http://api.ipinfodb.com/v3/ip-city/?key=" +api_key+"&ip="+ip_address+"&format=json"
try:
api_response = urllib2.urlopen(api_endpoint)
try:
return json.loads(api_response.read())
except (ValueError, KeyError, TypeError):
return "JSON format error"
except IOError, e:
if hasattr(e, 'code'):
return e.code
elif hasattr(e, 'reason'):
return e.reason
api_key = "YOUR_API_KEY"
ip_address = "IP_ADDRESS"
data = getIPAddress(api_key,ip_address)
#print data
if data['statusCode'] == "OK":
print "IP: "+ ip_address
print "API Status:"+ data['statusCode']
print "Country:"+ data['countryName']
print "Region:"+ data['regionName']
print "City:"+ data['cityName']
print "Latitude:"+ data['latitude']
print "Longitude:"+ data['longitude']
else:
print data['statusCode']
print data['statusMessage']
@18213020-18213038
Copy link

how can i get the api key?

Copy link

ghost commented Oct 15, 2016

I am getting an error in the line 15.. Don't know why :(

@pragatikawade94
Copy link

how can i get api key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment