Geo target your visitors

Author: Mattias (mattias@999tutorials.com)
Categories: General www, PHP
 Find out what countries your visitors come from. Perfect for displaying different ads for different countries
The tutorial:

Digg this, Post to del.icio.us,

Have you ever wanted to find out where a visitor lives?

I had the need a week ago when an ad company said that they had lots of advertisers that needed UK visitors. So they asked if I could show their ads for all my UK visitors. Now I have a solutions that I thought that I would share with you.

First of all download and unpack Maxminds geoip database. It's free (atleast this version) and can find out what country a visitor come from depending on their IP address. They say it's 97% accurate.

Download the database and unzip (gunzip -d GeoIP.dat.gz on linux)

Download the PHP api and save as geoip.inc

This database is pretty big, so we only want to use it as few times as possible. Because of that we will store a visitors countryCode in a cookie. So it's only the first time he/she visits our site we use the databse. The reset of the time the cookie i used. Smart :-)

function getCountryCode()
{
if(isset($_COOKIE["geoCode"]))
{
$countryCode = $_COOKIE["geoCode"];
}
else
{
include("geoip.inc");
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
$countryCode = geoip_country_code_by_addr($gi, $_SERVER["REMOTE_ADDR"]);
geoip_close($gi);
setcookie("geoCode", $countryCode, time()+15552000, "/", ".999tutorials.com", 0); //6 months cookie
}

return $countryCode;
}

Call this function and you will get US if the visitor is from USA and SE if the visitor is from Sweden.

So if you want to show special ads for all swedes you can use this code:

if(getCountryCode() == "SE")
{
echo "hello sweden";
include("ads/adsForSwedes.inc");
}
else
{
include("ads/adsForTheRestOfTheWorld.inc");
}

If you want show the visitors flag or send the visitor to a specific page... Use this function to find out the country. Just use your fantasy :-)

The database is updated once every month, in the beginning so make sure you update...

Good luck!!

Share this tutorial

Digg this, Post to del.icio.us,
 


eXTReMe Tracker