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

Comments

  1. User Avatar
    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. User Avatar
    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. User Avatar
    Catalin
    Permalink to comment#

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

  4. User Avatar
    andrew
    Permalink to comment#

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

  5. User Avatar
    Imraan
    Permalink to comment#

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

  6. User Avatar
    tweak tag
    Permalink to comment#

    Wonderful script and simple coding…. really effective.

    thanks…

  7. User Avatar
    One Price India
    Permalink to comment#

    How can i turn this script into wordpress plugin?

  8. User Avatar
    molbal
    Permalink to comment#

    I absolutetly agree with TeMC

  9. User Avatar
    StevenCodes

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

  10. User Avatar
    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. User Avatar
    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. User Avatar
    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. User Avatar
    Gabriel
    Permalink to comment#

    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");
    
    • User Avatar
      Gabriel
      Permalink to comment#

      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 );
      
    • User Avatar
      Kapil
      Permalink to comment#

      Thanks this is most simple and useful script for geoip.

  14. User Avatar
    Ashwin Pathak
    Permalink to comment#

    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.

  15. User Avatar
    sunainaraghu
    Permalink to comment#

    Hi, we can detect location by IP. Go through this site to detect location by IP http://www.melissadata.in/cloud-services/ip-locator-cloud-service

Submit a Comment

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.

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