A lot of times i have seen newbies and even PHP pros struggling to find any method of implementing zipcode and country lookup !

This can be easily achieved with the help of Maxmind Geo API, They provide a exhaustive DB lookup functionality of IP adress . Which can be further translated into City, Country and Zipcode information ! . This API prove to be very useful in the web apps which require providing user specific content to the users.

For the usage you simply need to download the GeoLiteCity database (Updated monthly) from this link.Also download three more files namely geoipcity.inc and geoipregionvars.php and put all three files in a folder name inc. Change PATH TO YOUR ROOT PUBLIC_HTML FOLDER to your server public_html path.

Once all files are in place , Simply use the code given below to fetch the city, country , zipcode , langitude and longitude information from the GeoLiteCity database.
?

include("inc/geoipcity.inc");
include("inc/geoipregionvars.php");
$IP = $_SERVER['REMOTE_ADDR'];
$gi = geoip_open("PATH TO YOUR ROOT PUBLIC_HTML FOLDER/inc/GeoLiteCity.dat",GEOIP_STANDARD);
$record = geoip_record_by_addr($gi,$IP);
$city =  $record->city;
$country = $record->country_name;
$latitude = $record->latitude;
$longitude = $record->longitude;
geoip_close($gi);
	
include("inc/geoipcity.inc");
include("inc/geoipregionvars.php");
$IP = $_SERVER['REMOTE_ADDR'];
$gi = geoip_open("PATH TO YOUR ROOT PUBLIC_HTML FOLDER/inc/GeoLiteCity.dat",GEOIP_STANDARD);
$record = geoip_record_by_addr($gi,$IP);
$city =  $record->city;
$country = $record->country_name;
$latitude = $record->latitude;
$longitude = $record->longitude;
geoip_close($gi);

The function geoip_open() opens the database for reading and geoip_record_by_addr() uses the database and the ip to generate the record .

All information is embed into the variable $record in above given example. Which can be fetched namely via
?

Advertisements