In this short post, I’ll show you how to geolocate your visitors with PHP. First of all let’s have a look at what you’ll need :
- PEAR GeoIP
- MaxMind GeoLite Country
Installing PEAR GeoIP
Using your console or using the command prompt type :
pear install http://download.pear.php.net/package/Net_GeoIP-1.0.0RC1.tgz
If you used our 70% off coupon for Bluehost shared hosting, you might not have access to install packages. In this case, you can just download and install any GeoIP plugin for WordPress (if WordPress if your platform of choice).
Obtaining MaxMind GeoLite Country
The database can be downloaded freely here. Download it and put it in the same folder where your script will reside.
<?php require_once('Net/GeoIP.php'); $geoip = Net_GeoIP::getInstance('./GeoIP.dat'); $ip = getenv('REMOTE_ADDR'); $country = $geoip->lookupCountryName($ip); echo "Hi, you're from ".$country; ?>
Now let’s go through the lines of code. The first line tells us to include the GeoIP class, which we installed previously and then create a geoip object in line 5 from the database we downloaded.
Next, in line 6 we get the IP address of the visitor and finally we call the lookupCountryName method with the IP address as parameter in line 7 and it will return us the country.
The last line just outputs the country, for example, “Hi, you’re from Mauritius”. That’s it, now you know where your visitor’s from.