tutorial.jcwcn.com home / Web Design & Development / PHP / Web Traffic Analysis > text Go back Print

How to Get a Users Geo Location?

  2009-05-08 11:10:05  

Once you download all of the files. Extract them all and upload them to the same folder on your server.

Now to use the API we need to include a few files. Then we are going to open the database and check the users location:

view source
print?
1.include("geoip.inc");
2.include("geoipcity.inc");
3.include("geoipregionvars.php");
4.$gi = geoip_open("./GeoLiteCity.dat", GEOIP_STANDARD);
5.$rsGeoData = geoip_record_by_addr($gi, $_SERVER['REMOTE_ADDR']);
6.geoip_close($gi);

This will grab the information, but what can we do with it. To find out what variables you can use print out the array:

view source
print?
01.include("geoip.inc");
02.include("geoipcity.inc");
03.include("geoipregionvars.php");
04.$gi = geoip_open("./GeoLiteCity.dat", GEOIP_STANDARD);
05.$rsGeoData = geoip_record_by_addr($gi, $_SERVER['REMOTE_ADDR']);
06.geoip_close($gi);
07.  
08.print "<pre>";
09.print_r($rsGeoData);
10.print "</pre>";

The results should output something like this:

geoiprecord Object
(
    [country_code] => US
    [country_code3] => USA
    [country_name] => United States
    [region] => TN
    [city] => Memphis
    [postal_code] =>
    [latitude] => 35.1242
    [longitude] => -89.9521
    [area_code] => 901
    [dma_code] => 640
)

I ran the above code using a Memphis based proxy. As you can see MaxMinds database gives us:
Country Abbreviation in two formats,
Full country name,
Region (state/province),
City,
Postal code (this usually works but is blank in the example),
Latitude,
Longitude,
Area Code,
DMA code (Designated Market Area as in Nielsen Media tv/radio market areas in the US)

Ok so now that we know what everything is, all we have to do is echo the results in the proper places. For example:

view source
print?
1.echo $rsGeoData->city;
2.echo ' ,';
3.echo $rsGeoData->region;

Would out put: Memphis, TN.
So if you were going to use this in a template you would use something like this in the header:

view source
print?
01.<?php
02.include("geoip.inc");
03.include("geoipcity.inc");
04.include("geoipregionvars.php");
05.$gi = geoip_open("./GeoLiteCity.dat", GEOIP_STANDARD);
06.$rsGeoData = geoip_record_by_addr($gi, $_SERVER['REMOTE_ADDR']);
07.geoip_close($gi);
08.  
09.$location $rsGeoData->city.','.$rsGeoData->region;
10.  
11.?>

Then in your template wherever you want the City, State to display simple:

view source
print?
1.<h1>Meet girls near <?php echo $location;?></h1>

The your site might look something like this:
php geo coding



/Web-Design/PHP/Web-Traffic-Analysis/2009-05-08/13869.html