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; 

Reference URL


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

  3. Catalin
    Permalink to comment#

    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. Imraan
    Permalink to comment#

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

  6. tweak tag
    Permalink to comment#

    Wonderful script and simple coding…. really effective.


  7. One Price India
    Permalink to comment#

    How can i turn this script into wordpress plugin?

  8. molbal
    Permalink to comment#

    I absolutetly agree with TeMC

  9. StevenCodes

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

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

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

      Thanks this is most simple and useful script for geoip.

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

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.