• Skip to content
  • Skip to primary sidebar

The html blog

The web sandbox

You are here: Home / php / Geolocate your visitors with PHP (part 1)

Geolocate your visitors with PHP (part 1)

September 29, 2017 By thehtmlblog Leave a Comment

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.

The code

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

Walkthrough

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.

In the second part of this article I’ll show you how to use the script to visually map your visitors using Google Maps. You can have a little preview of the script here.

Filed Under: php Tagged With: country, geoip, google maps, maxmind, net, pear, PHP, tutorial

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Subscribe and never miss a post

Categories

  • Hosting
  • Javascript
  • php
  • Web
  • XML

Copyright © 2021 · htmlblog.net