Mar
24

Track visitor's geo location with PHP

24 Mar 2009 by tonie in PHP

Have you ever wondered how do those adultfriendfinder.com ads know exactly which city you're browsing from? It might look complicated and close to impossible, but in fact I found a really simple way of achieving the same effect. Well, here's how I did it for one of my client's projects. I used MaxMind's open source database, which matches IPs against countries (cities as well). Also you're going to need an PHP API to make your work a piece of cake. For my project I used MaxMinds open PHP API. So, go ahead and download the free version of the database and the GeoIP.php file, I have attached to this post. Next, create a directory named geo and put everything you've downloaded in there. Copy and paste the following script:

<?php
// include class
include("geo/GeoIP.php");

//get user ip
$ip=$_SERVER['REMOTE_ADDR'];

// create instances
$geoipcity = Net_GeoIP::getInstance('geo/GeoLiteCity.dat');
$geoip = Net_GeoIP::getInstance('geo/GeoIP.dat');

// init vars
$country = $geoip->lookupCountryName($ip);
$countryCode = $geoip->lookupCountryCode($ip);
$location = $geoipcity->lookupLocation($ip);
$city = $location->city;
// close database
$geoip->close();

//print information
echo $country.'('.$countryCode.') '.$city;
?>

Simple, isn't it?

Attachments

geoip.rar (10 KB)

Tagged as: geo location, php, statistics

Speak your mind ( 2 Comments)

#1 by Jamie Dunne on 4/9/09

Nice workaround ... but if you want something even more accurate, easier to implement and also Free try this code snippet that uses Google's own GEO location database.. No API or anything needed.. here's the code..


if(typeof(google.loader.ClientLocation.address.city) != null) {
document.write(google.loader.ClientLocation.address.city);
} else {
document.write("Default Location Text")
}


nice eh ? :)
-JD
http://jamiedunne.com/blog

#2 by tonie on 9/9/09

Thanks for sharing this. You forgot to mention that you'll have to include google's jsapi in order for this snippet to work: <script type="text/javascript" src="http://www.google.com/jsapi"></script>

If you liked the article and want to contribute to it, please feel free to leave your comment. HTML tags are not allowed, but you can use the following BBCode to enhance your message: [url] [quote] [code] [b] [i] [u] [color].