Using GeoIP for Geolocation of Users with PHP

Sometimes you just need to know what country your site visitors are coming from, for example, for advertising or customizing content or language. This is when a tool like MaxMind's GeoIP proves very useful. It let's you look up a user's location based on the IP they are coming from.

MaxMind makes available both a commercial and a free database. In this article, we're going to use the free one but if you need more precision, then consider purchasing the commercial version.

Getting Started

First, download :


and place them into your website directory. Unzip GeoLiteCity.dat.gz.

Below is some example code to get you started.

<?php

// include functions
include("geoip.inc");

// read GeoIP database
$gi = geoip_open("GeoLiteCity.dat", GEOIP_STANDARD);

$remoteip = $_SERVER['REMOTE_ADDR'];
$rsGeoData = geoip_record_by_addr($gi,$remoteip);
$city = $rsGeoData->city;
$region = $rsGeoData->region;
$postalcode = $rsGeoData->postal_code;
$countryname = $rsGeoData->country_name;

// Do something with the data

// close database handler
geoip_close($gi);

?>

Most Recent Visitors

This is some example code showing the countries of people who have visited my website.

\n"; print "\n"; print "IP\n"; print "City\n"; print "Region\n"; print "PostCode\n"; print "Country Name\n"; print "\n"; $rate = 13; for ($i=0; $i\n"; print "$ips[$i]\n"; print "$rsGeoData->city\n"; print "$rsGeoData->region\n"; print "$rsGeoData->postal_code\n"; print "$rsGeoData->country_name\n"; print "\n"; } } print "\n"; geoip_close($gi); include "../footer.php"; ?>