Jun
29
2011

Get Location From User IP Address

For many of the websites that I work with and manage, IP addresses are collected; primarily as a means to combat spammers, secondarily because it’s always interesting to this great PHP script to turn those nonsensical IP’s into a nicely formatted text output which (so far after 12 hours) has shown to be very accurate!

I’ve modified the PHP script from <a title=”Get GEO IP Information” href=”http://css-tricks.com/snippets/php/get-geo-ip-information/”>this article to more effectively format the output to my needs (City, State, Country), and it can easily be re-modified to display any variant that you’d like to output by changing the highlighted line in the code below:

function geoCheckIP( $ip )
{
    //check, if the provided ip is valid
    if( !filter_var( $ip, FILTER_VALIDATE_IP ) )
    {
        throw new InvalidArgumentException("IP is not valid");
    }

    //contact ip-server
    $response=@file_get_contents( 'http://www.netip.de/search?query='.$ip );

    if( empty( $response ) )
    {
        throw new InvalidArgumentException( "Error contacting Geo-IP-Server" );
    }

    //Array containing all regex-patterns necessary to extract ip-geoinfo from page
    $patterns=array();
    $patterns["domain"] = '#Domain: (.*?) #i';
    $patterns["country"] = '#Country: (.*?) #i';
    $patterns["state"] = '#State/Region: (.*?)<br#i';
    $patterns["town"] = '#City: (.*?)<br#i';

    //Array where results will be stored
    $ipInfo=array();

    //check response from ipserver for above patterns
    foreach( $patterns as $key => $pattern )
    {
        //store the result in array

        $ipInfo[$key] = preg_match( $pattern, $response, $value ) && !empty( $value[1] ) ? $value[1] : 'not found';
    }
    
    /*I've included the substr function for Country to exclude the abbreviation (UK, US, etc..)
    To use the country abbreviation, simply modify the substr statement to:
    substr($ipInfo["country"], 0, 3)
    */
    $ipdata = $ipInfo["town"]. ", ".$ipInfo["state"].", ".substr($ipInfo["country"], 4);

    return $ipdata;
}

Now, assuming that you’ve collected your IP addresses somewhere- you simply call up the function, including the IP address as in the example below:

$ip = '71.34.177.144';
echo geoCheckIP( $ip ); //Returns "Urbandale, Iowa, US"

If you need to capture the IP address of a user, you’ll want to use the “$_SERVER[‘REMOTE_ADDR’];” call, which I prefer to wrap into a PHP constant, ie…

$user_ip = $_SERVER['REMOTE_ADDR'];

That’s it!

The original function (before I modified it) may be located here.

10 Comments + Add Comment

  • İ will try this code.. if works you’re great. thanks anyway

  • Hello
    the problem is when I upload it to my website: http://ourbestshop.com/ it not worked

  • Hi there, original code works, but yours doesn’t for some reason, just stops the script dead with nothing output

    • Check for special characters in the code, sometimes syntax highlighters throw unexpected and annoyingly hidden characters in copy-paste output

  • hi! Thanks for share!!! It,s work for me. How can i make a my ip widget ?
    Thanks again!

  • hi friends
    i have edited this code now its working you can see know here
    http://aamaadmiweb.com/socialservices/how-to-store-ip-address-location-in-php-code

  • That’s nice tutorial,
    I think geloPlugin also a good solouion for it.
    geoplugins also works fine, I used it.
    I will use your method, I hope it will be works fine.
    Is it possible to extract ip information without third party website api?

Leave a comment