City , Country and zipcode lookup via Ip address in PHP

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 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.


$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;


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

print_r ($record);

All variable name are self-explanatory to include the desired data !

Let us know if you encounter any issues in deploying this tutorial

Alternatively if you are making a google mashup, Try out this excellent book that i used for my mashups

20 thoughts on “City , Country and zipcode lookup via Ip address in PHP”

  1. Pingback:
  2. I ran into this great post yesterday, and it ALMOST worked for what I needed. All the other variables like city and country returned fine, but did you have trouble getting the postal_code variable to work? It just returns blank for me. Unfortunately, all i need is the postal_code.

  3. now i remember reading about the inconsistency. I did find a solution combining other zipcode data. Still gotta thank you for this post for I would have had to drop atleast $300 plus monthly fees on the services out there. Kudos! 😀

  4. This is nice blog and i like this blog. you want to zip code data and maps here available and download immediately. We hope zip code data and maps much useful.

  5. well, postcode or zip code was the main thing that I wanted to achieve and that’s inconsistent in this script finally huh …

    wasted my couple of hours.

  6. @Ranjeet Unfortunately can’t do much about it. I guess you’ve a paid version too. Check that out.

Leave a Reply