Code Snippet

Home » Code Snippets » PHP » Get Geo-IP Information

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;
       }

?>

Subscribe to The Thread

  1. 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. I really needed this, thanks!

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

    • Brian

      $_SERVER['REMOTE_ADDR']

      So, you could call the function like this:

      $ip=$_SERVER['REMOTE_ADDR'];
      geoCheckIP($ip);

  4. 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. 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. 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. 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. Anthony

    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

  9. jatinder

    Thanks, i needed this one.
    finally this script is working without any errors,

  10. 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

  11. Debrata V

    Hi There,
    Really cool, the script is neat and lot of ideas bubblling in my head ;)

    Thanx
    Deb

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~