Get the client country based on ip address  [ 909 views ]

Goal: find the client on the map

I was supprised when I examined my server’s stat. There were many client from unknown country. This is not too good. I remember an old solution depends on ip2c database. This is nice and easy, but to keep the database updated not too confortable.

1. database solution

I have a simple table (ta_ip2c) with the ip2c data,


and I can read the data width a simple select:

SELECT * FROM ta_ip2c WHERE $ip_num BETWEEN begin_ip_num AND end_ip_num;

$ip_num is the converted ip $ip_num = ip2long($ip)

2. online solution (
The method is the same but no local database. Just ask the server like this:

/* or
sample call
$ip = ''; //or any other IP here
$s = file_get_contents(''.$ip);
  case '0':
    echo 'Something wrong';
  case '1':
    $reply = explode(';',$s);
    echo '<br>Two-letter: '.$reply[1];
    echo '<br>Three-letter: '.$reply[2];
    echo '<br>Full name: '.$reply[3];
  case '2':
    echo 'Not found in database';

The output is very simple:

+ your request has not been processed due to invalid syntax
    + e.g. bad IPv4 like
    + e.g. bad decimal like 2a3b4c or bigger than MAX_INT

+ contains two-letter (ISO 3166) and three-letter country codes, and a full country name
+ country name may be multi-word and contain spaces
+ e.g. we take your IP:
    + URL looks like this:
    |                       or
    + resulting string is:  1;GB;GBR;United Kingdom

+ given ip/dec not found in database or not yet physically assigned to any country
#sidebar a { color:#fff; } #sidebar ul ul li { color: #DEF585; } #sidebar h2 { color: #fff; } #sidebar ul p, #sidebar ul select { color: #BEDDBE; } #backfly { background: url(images/golfBallWallPaper.jpg) left bottom fixed repeat-x #65a51d; }