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
| 02 |
function getCountryCode() |
| 04 |
if(isset($_COOKIE["geoCode"])) |
| 06 |
$countryCode = $_COOKIE["geoCode"]; |
| 11 |
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD); |
| 12 |
$countryCode = geoip_country_code_by_addr($gi, $_SERVER["REMOTE_ADDR"]); |
| 14 |
setcookie("geoCode", $countryCode, time()+15552000, "/", ".999tutorials.com", 0); //6 months cookie |
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:
| 1 |
if(getCountryCode() == "SE") |
| 4 |
include("ads/adsForSwedes.inc"); |
| 8 |
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…
|