In this post, I’ll show How to lookup the country, region, city, postal code, latitude, and longitude by IP Address. There are some free online tools to get those information from an IP Address. Today, I’ll use one of them, Maxmind as a demonstration.
First, you need to download the latest GeoLite City database in Binary Format from Maxmind. It’s FREE, updated monthly and accuracy up to 99.5%. You also need to download their PHP API to parse the Binary database and get information from an input IP Address.
1. PHP sample
<?php include("geoipcity.inc"); include("geoipregionvars.php"); $gi = geoip_open("M:/Web/htdocs/maxmind/GeoLiteCity.dat",GEOIP_STANDARD); $record = geoip_record_by_addr($gi,"67.227.221.249"); print "country_code: " . $record->country_code . "<br>"; print "country_code3: " . $record->country_code3 . "<br>"; print "country_name: " . $record->country_name . "<br>"; print "region: " . $record->region . "<br>"; print "region_name: " . $GEOIP_REGION_NAME[$record->country_code][$record->region] . "<br>"; print "city: " . $record->city . "<br>"; print "postal_code: " . $record->postal_code . "<br>"; print "latitude: " . $record->latitude . "<br>"; print "longitude: " . $record->longitude . "<br>"; print "metro_code: " . $record->metro_code . "<br>"; print "area_code: " . $record->area_code . "<br>"; geoip_close($gi); ?> |
2. Output
country_code: US country_code3: USA country_name: United States region: MI region_name: Michigan city: Lansing postal_code: 48917 latitude: 42.7257 longitude: -84.636 metro_code: 551 area_code: 517 |
Download the demonstration source code above. It’s include the sample file, all included files and GeoLiteCity.dat.