Tuesday, May 3, 2011

Geolocate Your Visitors By IP Address

I found this real good service provided by http://www.geoplugin.com/. It is accurate and free. It provides a lot of information besides the location from IP Address, like currency.

The geoplugin service can be used from the client using javascript, it has JSON/PHP/XML services too.

PHP Code Snippets:

To find out the IP Address of your visitor I use the following PHP code:

    if (getenv(HTTP_X_FORWARDED_FOR)) {
     $pipaddress = getenv(HTTP_X_FORWARDED_FOR);
     $ipaddress = getenv(REMOTE_ADDR);
     echo "Your Proxy IP address is : ".$pipaddress." (via $ipaddress)<br />" ;
    } else {
     $ipaddress = getenv(REMOTE_ADDR);
     echo "Your IP address is : $ipaddress<br />";

Now, using the geoplugin service
$geolocation = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ipaddress));
echo '<pre>';
echo '</pre>';

Will give you a whole lot of information. To get specific information, try...
echo 'Country:'.$geolocation['geoplugin_countryName'].'<br />';
echo 'City:'.$geolocation['geoplugin_city'];