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 == '' || $ip == 'localhost')
            $ip = '';

        $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 = '' . urlencode($ip);
        $ch = curl_init();
        $curl_opt = array(
            CURLOPT_HEADER      => 0,
            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);
        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;
          return $default; 


  1. User Avatar
    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 service isn’t terribly accurate… I’m in downtown San Francisco it thinks I’m in Santa Clara, CA. :(

  3. User Avatar
    Permalink to comment#

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

  4. User Avatar
    Permalink to comment#

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

  5. User Avatar
    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.


  7. User Avatar
    One Price India
    Permalink to comment#

    How can i turn this script into wordpress plugin?

  8. User Avatar
    Permalink to comment#

    I absolutetly agree with TeMC

  9. User Avatar

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

  10. User Avatar
    Cj Belo
    Permalink to comment#


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

    $ip = ''; // Your IP Address
    $tags = get_meta_tags("$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
    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:

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

    How about ?

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

    $.get("", function(response) {
    }, "jsonp");
    • User Avatar
      Permalink to comment#

      Or alternativly with php:

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

      Clean php code:

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


      Array (
        [ip] =>
        [hostname] => No Hostname
        [city] => Columbus 
        [region] => Ohio 
        [country] => US 
        [loc] => 39.9612,-82.9988
        [postal] => 43218 );
    • User Avatar
      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:
    It’s using a different API for getting IP information and also it’s fast and shows correct informations.

  15. User Avatar
    Permalink to comment#

    Hi, we can detect location by IP. Go through this site to detect location by IP

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