Get Geo-IP Information

Requests a geo-IP-server to check, returns where an IP is located (host, state, country, town).

<?php
       $ip='94.219.40.96';
       print_r(geoCheckIP($ip));
       //Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen )

       //Get an array with geoip-infodata
       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: (.*?)&nbsp;#i';
               $patterns["country"] = '#Country: (.*?)&nbsp;#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';
               }

               return $ipInfo;
       }

?>

Comments

  1. User Avatar
    David
    Permalink to comment#

    You should consider caching results too as it will speed it up considerably.
    For small low traffic websites it won’t be too bad but if your expecting to grow it’s something you must look into now. You should also consider that you are relying on the website being up and returning data in a specific way so the regexes could become outdated or broken in the future.
    Just some things to consider.

  2. User Avatar
    Andrew Champ
    Permalink to comment#

    I really needed this, thanks!

  3. User Avatar
    Mathew
    Permalink to comment#

    What would be the best method of getting the users IP address to use with this?

    • User Avatar
      Brian
      Permalink to comment#

      $_SERVER[‘REMOTE_ADDR’]

      So, you could call the function like this:

      $ip=$_SERVER[‘REMOTE_ADDR’];
      geoCheckIP($ip);

  4. User Avatar
    Neil Trigger
    Permalink to comment#

    I wish I had seen this about 6 months ago… it works brilliantly! I’m going to put it to work on loads of websites right now!

  5. User Avatar
    Neil Trigger
    Permalink to comment#

    I have been playing and thought this might be useful too… it allows you to redirect or echo a silly statement depending on the user’s location:

    $my_array=geoCheckIP($ip);

    foreach ($my_array as $key => $value){
    if($key=='country'){
    #switch on the country:
    switch ($value) {
    case 'GB - United Kingdom':
    echo "You are visiting from the UK! We love the british!";
    break;
    case 'NZ - New Zealand':
    echo "You're visiting from New Zealand. What's the weather like down under?";
    break;
    case 'US - United States':
    echo "You're visiting from The USA. It must be nice to be in the home of the brave. I'd love to go, but I'm too scared!";
    break;
    case 'CA - Canada':
    echo "You're visiting from Canada. Is it snowing?";
    break;
    case 'AU - Australia':
    echo "You're visiting from Australia. Does the blood rush to your head?";
    break;
    }
    echo '
    '.$key.': '.$value;
    }

    }

  6. User Avatar
    ryan
    Permalink to comment#

    cool – im needing this so that certain states except nebraska can only see some pages.
    what would the entire script look like in this case?

    ie:
    if your in nebraska – it redirects to URL A
    if outside nebraska – it redirects to URL B

    thanks – ryan

  7. User Avatar
    Matalin
    Permalink to comment#

    Hi All,

    This is the first part of a formula to get the region automatically from ip.

    In my wufoo form I currently have a region dropdown that is required. Would we be able to use a version of this, possibly with url modifications to dump the region response into hidden wufoo fields?

    Thanks!!

    Matalin

  8. User Avatar
    Anthony
    Permalink to comment#

    Thanks great share i needed this will be very helpful for detecting my users real IP an location because for the past few days i am being faced with some spammers.

    http://www.gysms.com

    • User Avatar
      Quentin
      Permalink to comment#

      Why you put their adress on this site if they’re spammers ?
      If you’re a developer you should know you’re doing them some backlinking here that’s really not clever …

  9. User Avatar
    Danny
    Permalink to comment#

    tidy and functional ….any know how to use this to display post based on user location? example: an event listing site displaying events in user’s location.
    thanks

  10. User Avatar
    Grahame
    Permalink to comment#

    This is pretty cool, but I don’t think I’ll ever use it on a production server because of the reliance on a third party. What happens if netip.de shuts down all of a sudden?

  11. User Avatar
    Kedar
    Permalink to comment#

    Hi dude, I want to create my own url shorning service.How to do that?

  12. User Avatar
    Savion
    Permalink to comment#

    Hi, the state pattern is throwing me a “not found” error. Please help…

  13. User Avatar
    Vancouver
    Permalink to comment#

    I too have experienced the “not found” attribute when making websites using WordPress platform.

  14. User Avatar
    jasmeet
    Permalink to comment#

    Array ( [domain] => localhost [country] => – [state] => not found [town] => not found )
    any help???

    • User Avatar
      boed
      Permalink to comment#

      hey, dont use this code from localhost…
      he write $ip with static number no $ip=$_SERVER[‘REMOTE_ADDR’];
      because not working from there

  15. User Avatar
    jasmeet
    Permalink to comment#

    thanks

  16. User Avatar
    Alberto Mota
    Permalink to comment#

    Nice, we’ve been using something similar as well.. for all of those concerned about relying on a 3rd party web service, think the key thing is to keep it detached from any service in particular, so you can easily switch to a different one if needed; this Drupal module does that really nicely for instance: https://drupal.org/project/smart_ip‎

  17. User Avatar
    mfnstatus
    Permalink to comment#

    Thanks great share i needed this will be very helpful for detecting my users real IP an location because for the past few days i am being faced with some spammers.

  18. User Avatar
    Gabriel
    Permalink to comment#

    http://ipinfo.io/ is much more exact. And it’s very simple to use with PHP or AJAX.

    Have a look at the developer-info: http://ipinfo.io/developers

  19. User Avatar
    Grig
    Permalink to comment#

    function getRealIpAddr()
    {
    if (!empty($_SERVER[‘HTTP_CLIENT_IP’])) //check ip from share internet
    {
    $ip=$_SERVER[‘HTTP_CLIENT_IP’];
    }
    elseif (!empty($_SERVER[‘HTTP_X_FORWARDED_FOR’])) //to check ip is pass from proxy
    {
    $ip=$_SERVER[‘HTTP_X_FORWARDED_FOR’];
    }
    else
    {
    $ip=$_SERVER[‘REMOTE_ADDR’];
    }
    return $ip;
    }

  20. User Avatar
    Grig
    Permalink to comment#

    function get_ip_address() {
    // check for shared internet/ISP IP
    if (!empty($_SERVER[‘HTTP_CLIENT_IP’]) && validate_ip($_SERVER[‘HTTP_CLIENT_IP’])) {
    return $_SERVER[‘HTTP_CLIENT_IP’];
    }

    // check for IPs passing through proxies
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // check if multiple ips exist in var
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) {
            $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($iplist as $ip) {
                if (validate_ip($ip))
                    return $ip;
            }
        } else {
            if (validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
                return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED']) && validate_ip($_SERVER['HTTP_X_FORWARDED']))
        return $_SERVER['HTTP_X_FORWARDED'];
    if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
        return $_SERVER['HTTP_FORWARDED_FOR'];
    if (!empty($_SERVER['HTTP_FORWARDED']) && validate_ip($_SERVER['HTTP_FORWARDED']))
        return $_SERVER['HTTP_FORWARDED'];
    
    // return unreliable ip since all else failed
    return $_SERVER['REMOTE_ADDR'];
    

    }

  21. User Avatar
    Grig
    Permalink to comment#

    function validate_ip($ip)
    {
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
    return false;
    }
    return true;
    }

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

Submit a Comment

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag