Grow your CSS skills. Land your dream job.

Last updated on:

Detect Location by IP

Returns "City, State" if found otherwise the default set at the top.

function detect_city($ip) {
        
        $default = 'UNKNOWN';

        if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
            $ip = '8.8.8.8';

        $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
        
        $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
        $ch = curl_init();
        
        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION  => 1,
            CURLOPT_HEADER      => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_USERAGENT   => $curlopt_useragent,
            CURLOPT_URL       => $url,
            CURLOPT_TIMEOUT         => 1,
            CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
        );
        
        curl_setopt_array($ch, $curl_opt);
        
        $content = curl_exec($ch);
        
        if (!is_null($curl_info)) {
            $curl_info = curl_getinfo($ch);
        }
        
        curl_close($ch);
        
        if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) )  {
            $city = $regs[1];
        }
        if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) )  {
            $state = $regs[1];
        }

        if( $city!='' && $state!='' ){
          $location = $city . ', ' . $state;
          return $location;
        }else{
          return $default; 
        }
        
}

Reference URL

Comments

  1. TeMc
    Permalink to comment#

    Note that this probably doesn’t scale very well as it’s depending on a third party service, and it depends on the html output from that service. Could break at any time and might slow down your page.

    (of course sanitize anything you get from here, assume nothing)

  2. Benjamin Knight
    Permalink to comment#

    Unfortunately the ipinfodb.com service isn’t terribly accurate… I’m in downtown San Francisco it thinks I’m in Santa Clara, CA. :(

  3. Catalin
    Permalink to comment#

    Hei.
    Could I know how to obtain information for how far the IP is located from me? Thanks.

  4. andrew
    Permalink to comment#

    would this help me to open a feature on a website to a determinate state???

  5. Permalink to comment#

    i am from kolkata, but it is showing that i am from mumbai !!

  6. Permalink to comment#

    Wonderful script and simple coding…. really effective.

    thanks…

  7. How can i turn this script into wordpress plugin?

  8. Permalink to comment#

    I absolutetly agree with TeMC

  9. Great snippet, could use a little updating though!
    Your Friend, StevenCodes.

  10. Cj Belo
    Permalink to comment#

    Hi,

    Try this in php, this is also using a third party site though.

    
    
    $ip = '127.0.0.1'; // Your IP Address
    $tags = get_meta_tags("http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress=$ip");
    //var_dump($tags); // Check the output
    
    echo $tags['city'] . ', ' . $tags['country'];
    
    
    

    This is the shortest code I’ve used in detecting a location via IP so far.

    :)

  11. Iren
    Permalink to comment#

    As for me, if to use the 3d party service it’s better to rely on some services which are designed to be accessed outside and not parse any HTML pages. For example, here is a service which provides a good JSON or XML interfaces to access geo-ip data: http://smart-ip.net/geoip-api

  12. nuntius
    Permalink to comment#

    Those reporting faulty locations need to remember that an IP only gets you as far as ISP network segment that gave the IP. So if you are in a densely populated area with a dense network infrastructure it will be more accurate, but if you are in a more rural area or foreign location the network segment could be quite large.

  13. How about ipinfo.io ?

    you can just use this: http://ipinfo.io/json
    and you get an perfect json output.. but you have to use it with js:

    $.get("http://ipinfo.io", function(response) {
        console.log(response.ip, response.country);
    }, "jsonp");
    
    • Or alternativly with php:

      One php line:
      print_r(json_decode(file_get_contents('http://ipinfo.io/'.$_SERVER['REMOTE_ADDR'].'/json'), true));

      Clean php code:

      function getClientIPInfo($ip = $_SERVER['REMOTE_ADDR']) {
          $json_data = file_get_contents('http://ipinfo.io/'.$ip.'/json');
          $data = json_decode($json_data, true);
          return $data;
      }
      

      returns:

      Array (
        [ip] => 11.22.33.44
        [hostname] => No Hostname
        [city] => Columbus 
        [region] => Ohio 
        [country] => US 
        [loc] => 39.9612,-82.9988
        [postal] => 43218 );
      
  14. The API which you are using is quite slow and also sometimes shows wrong information, check this one: http://codicious.blogspot.in/2014/04/getting-ip-address.html
    It’s using a different API for getting IP information and also it’s fast and shows correct informations.

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".