PHP Geo IP Locator

Very useful function for tracking your visitors, localized languages, auto completion of registration forms (address) and anything you can think of.

function geoip($ip = "127.0.0.1"){
    
    if($ip == "127.0.0.1"){$ip = $_SERVER["REMOTE_ADDR"];}//if no IP specified use your own

    $ch = curl_init();//faster than file_get_contents()
    curl_setopt($ch, CURLOPT_URL,'http://www.geoplugin.net/php.gp?ip='.$ip);//fetch data from geoplugin.net
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    $curl = curl_exec($ch);
    curl_close($ch);
    
    $geoip = unserialize($curl);
    return $geoip["geoplugin_countryName"]." ".$geoip["geoplugin_city"];//return country and city
}


Let's find out where is Google (according to IP)...

X:\WEBARTO>ping www.google.com

Pinging www.l.google.com [74.125.87.147] with 32 bytes of data:

Reply from 74.125.87.147: bytes=32 time=70ms TTL=50
Reply from 74.125.87.147: bytes=32 time=69ms TTL=50
Reply from 74.125.87.147: bytes=32 time=107ms TTL=50
Reply from 74.125.87.147: bytes=32 time=70ms TTL=50

PHP:

echo geoip("74.125.87.147");

Output:

United States Mountain View (we've nailed it!)


If contacting third party site is slowing down your site, you can download MaxMind GeoLiteCity database which you can run on your server (~ 130MB size).

Download: http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/GeoLiteCity_20100401.zip

©2009-2011 Webarto • web design & development • Tuzla // Sarajevo // Beograd