Get the client country based on ip address [ 1735 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 (ip2c.org)
The method is the same but no local database. Just ask the server like this:
/* http://ip2c.org/?ip=XXX.XXX.XXX.XXX or http://ip2c.org/XXX.XXX.XXX.XXX sample call */ $ip = '89.168.70.220'; //or any other IP here $s = file_get_contents('http://ip2c.org/'.$ip); switch($s[0]) { case '0': echo 'Something wrong'; break; case '1': $reply = explode(';',$s); echo '<br>Two-letter: '.$reply[1]; echo '<br>Three-letter: '.$reply[2]; echo '<br>Full name: '.$reply[3]; break; case '2': echo 'Not found in database'; break; }
The output is very simple:
0;;;WRONG INPUT | + your request has not been processed due to invalid syntax | + e.g. bad IPv4 like 300.400.abc.256 + e.g. bad decimal like 2a3b4c or bigger than MAX_INT 1;CD;COD;COUNTRY | + 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: http://ip2c.org/?ip=89.168.70.220 | or | http://ip2c.org/89.168.70.220 | + resulting string is: 1;GB;GBR;United Kingdom 2;;;UNKNOWN | + given ip/dec not found in database or not yet physically assigned to any country