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?
I see no point on posting a comment with code, if the code used to comment is not complete or buggy code, this guy seem to envy a great article with simple code, instead of making a critic i would be better to paste a complete unbuggy code.
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].
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