WordPress IP to Country Plugin

WordPress IP to Country plugin is adapted from [IP-to-Nation plugin for WordPress](http://frenchfragfactory.net/ozh/archives/2004/08/27/ip-to-nation-plugin/). The only difference is that my IP to Country plugin uses (surprise!) the [IP to Country database](http://ip-to-country.webhosting.info/) instead of [IP to Nation database](http://www.ip2nation.com). There is also the [GeoIP plugin](http://wordpress.org/support/10/10274) which uses the [GeoIP database](http://www.maxmind.com).

I’ve been using the IP to Nation plugin, but I feel that the database is not good enough. An IP from Germany, for example, sometimes get identified as from Europe. My previous experience with the GeoIP database was much better, but the plugin itself seems to be unmaintained. It was not hard to adapt the IP-to-Nation plugin to use IP to Country database since both uses database backend and uses similar algorithm. Thanks to [Ozh](http://frenchfragfactory.net/ozh/archives/2004/08/27/ip-to-nation-plugin/) for creating IP to Nation plugin in the first place.

**Requirement**

Any version of WordPress above 1.2 should suffice. Some basic knowledge of PHP and editing WordPress template are also required.

**Installation**

Next, the installation instruction. The installation is a bit more involved than IP to Nation since IP to Country only provides its data as a CSV file, not as SQL dump file.

1. Download the [IP to Country database](http://ip-to-country.webhosting.info/node/view/6)
2. Unzip it to get a CSV file.
3. Create the table ‘iptocountry’ to store the database: `CREATE TABLE iptocountry (ip_from int(4) unsigned, ip_to int(4) unsigned, country_code2 char(2), country_code3 char(3), country_name varchar(50));`
4. Create the cache table ‘iptocountry_cache’ if you wish to use caching. Caching is recommended for busy sites, but for smaller blogs it can unnecessarily waste space: `CREATE TABLE iptocountry_cache (ip int unsigned, country_code2 char(2), country_code3 char(3), country_name varchar(50));`
5. Populate the table: `load data infile ‘/path/to/ip-to-country.csv’ into table iptocountry fields terminated by ‘,’ enclosed by ‘”‘ lines terminated by ‘\r\n’;`. *Note*: if you uploaded the CSV file using FTP in ASCII mode, you need to do this query instead: `load data infile ‘/path/to/ip-to-country.csv’ into table iptocountry fields terminated by ‘,’ enclosed by ‘”‘ lines terminated by ‘\n’;`. You might not be able to do this if your database user lacks privilege, in that case, you will need to write a CSV parser to do this, should be easy enough if you have some programming skill. If you wrote one, please share it so others can benefit. *Note*: [Praveen](http://www.praveen.ws/) has made available an [SQL dump of IP to Country data](http://www.praveen.ws/journal/2005/03/30/ip-to-country-plugin-is-now-up/). You can use that if you have difficulties loading CSV file.
6. Download [the plugin](https://priyadi.net/wp-content/plugins/wp_ip2country.txt), rename it into wp_ip2country.php and put it in your wp-content/plugins directory.
7. If you wish to use caching, please enable it near the top of the wp_ip2country.php file.
8. Activate the plugin from your WordPress plugin menu.
9. (optional) Get flag images. Ozh provides a download link [here](http://frenchfragfactory.net/ozh/archives/2004/08/27/ip-to-nation-plugin/), or you can also download another version from [GeoIP](http://www.maxmind.com/download/geoip/database/flag.zip).
10. Modify your templates as you see fit

**Available functions**

* `wp_ip2c_getCountryName($display, $ip)`: prints/returns country name, e.g. Indonesia
* `wp_ip2c_getCountryCode2($display, $ip)`: prints/returns two letter country code, e.g. id
* `wp_ip2c_getCountryCode3($display, $ip)`: prints/returns three letter country code, e.g. idn

The IP to Country database uses CAPITAL LETTERS exclusively. But with this plugin, the country name is always printed/returned with capital first letter in each word, and the country code is always printed/returned in lower case.

If $display is set to 1, the function will print the output. If $display is set to 0, the function will return the output so that you can use the returned values. $ip can be omitted, this way the function will use cached data from previous invocation. You can use this feature to minimize database lookups. If there is no cached data and $ip is not provided, the function will use the server variable $REMOTE_ADDR as the IP address to check.

**Examples**

This will display visitor’s country flag and name.


You are from


Put the following inside comment loop for displaying commenter country name and flag.


Posted from
<?php wp_ip2c_getCountryName(1,$comment->comment_author_IP); ?>
< ?php wp_ip2c_getCountryName(1); ?>

**Note**

IP to Country database is not normalized unlike IP to Nation. So, it takes a bit more space. In my case, IP to Country takes about 1.58 MB of space, and IP to Nation takes about 350 KB.

**Demonstration**

You are coming from ‘;
echo wp_ip2c_getCountryName(0); ?>
.

I hope this will deter people from making comment tests below :P

**Changelog**

2.0: Implements caching, useful for busy sites.

254 comments

  1. Hello, nice to see some other plugin on the same topic :)

    As for IP databases, I think each one can be better or worse than the other one depending on the IP. You say for example that ip2nation sometimes identifies Germany as “Europe”, I see that IP-to-Country identifies me as, on their website, “You are from United States and your IP Address is unknown.” which I think is kind of pathetic :) (I’m from France, and why the hell would my IP be unknown ?)

    It’ll be interesting nonetheless to see what feedback you’ll have from visitors and users from all over the world regarding accuracy of the database you’re using, I’m looking forward to see how it turns out :)

    Again, cheers !

  2. That’s probably simply a bug on their web site and their code choose United States by default :). I don’t know how accurate IP to Country is, this is my first time using it. I guess we’ll see how it goes.

    BTW, thanks for IP to Nation plugin…

  3. Make sure you use the GeoIP Flags and not the IP2Nation ones as some of the flags have different names… For example the GB flag for IP2Country is called flag_uk.gif in the IP2Nation collection, likewise there are issues for the European Flag…

  4. #15: I happen to use both. I unzipped GeoIP flags, then replaced them with IP2Nation. So I have both gb.gif and uk.gif.

    FYI, the IP2Nation version has about one dozen more flags than the GeoIP one. Some flags in GeoIP are in different size than the others. In IP2Nation, only one flag (Syria) is in different size than the others. So, I think this is an indication that the IP2Nation version is newer than GeoIP.

  5. Another test for Sydney Australia.

    I wonder if I can use this plugin to identify which countries I blog from, giving visitors a “last seen in” status box.

  6. #22: should be possible, but you will need something else. Your wordpress will need to store your IP address everytime you publish a post. Then this plugin can attempt to guess country of that IP address.

  7. Funny thing is that despite the number of users, US citizens seem highly unrepresented in the comments here. Wonder why? (Blah, blah, blah, if you want to flame me for that comment, visit my site, and don’t futz up Priyadi’s).

  8. After a long frustation that I was not able to load from the GeoIP CSV file (because of the lack of FILE priveliges in MySQL), I have loaded it on my local machine and created a SQL dump of the table. It is available at http://www.praveen.ws/journal/pub/iptocountry/iptocountry.tar.bz2
    I thought of sharing this because it may be of some use to the people who face problems like me.

    PS: BTW, I am not sure if the license of GeoIP allows to distribute the database in this way.

  9. For WP 1.5, we need to change the comments.php file in the current theme directory and add the following code to get it working.
    from <img src="/path-to/flags/flag_<?wp_ip2c_getCountryCode2(1, get_comment_author_IP())?>.gif" />
    <?wp_ip2c_getCountryName(1, get_comment_author_IP())?>

  10. #34: thank you for sharing!

    #36: no you don’t need get_comment_author_IP() on the second invocation. if you use get_comment_author_IP(), then query will be done twice. if you don’t, it will use cached data from the last invocation.

  11. Mas Pri,

    Saya kok tidak pernah bisa menampilkan gambar flagnya yah? Kalau saya pasang codenya yg utk flag selalu error. Tapi kalau tanpa flag sudah bisa sih. Kenapa yah? contoh yg di atas itu perlu ditambah prefix php apa lagi ya? saya sama sekali tidak tahu php nih. Mohon pencerahannya.

    Terima kasih sebelumnya.

  12. Mas Pri,

    Setelah saya kutak-katik lagi pelan2, ternyata sudah bisa jalan semua. Tapi pake code dr commentor #36. Maaf, sudah ngerecokin. Itu comments saya yg gagal tulis code dihapus saja bisa kan. Banyak sekali tuh. bikin kacau.

    Terima kasih.

  13. pluign yang bagus… erm.. kalo mas priyadi tambah fungsinya pasti lebih bagus seperti digabungkan seperti:-

    IP2Nation + Browser Detection + Gravatar = Webstat analysis

    Pasti enak deh.. oleh demkian, plugin ini bisa bekerja 3 dalam 1…. :)>-:d

  14. #56.. aduh kalo bisa jangan digabung2 gitu deh, gak semua org butuh semuanya soalnya. Kalo dipisah kecil2 akan membuatnya jadi lebih flexible dan ramping. You can always mix and match from smaller components, but it’d be harder to do it the other way around, i.e. removing parts you don’t need.

  15. #66: itu berhubungan dengan database mysql, coba hubungi sysadminnya. saya gak bisa kasih info detail karena tiap sistem beda-beda konfigurasinya.

  16. hi, I love this plugin alot but cant get it to work. I notice that the table I created has no index… is that right?
    Thanx:)>-

  17. Hi, I love the plugin, but cant get it to work. I have a feeling it might be mysql related. the fields are populated with this:
    N¢ýÝ=ÿÎKŸÃ5ÍépreÅ‘Fó¯wþ
    Any suggestions? I would really love to have this plugin on my site.
    Thank you,
    Robert

  18. Hi, i was able to get this working but had to change the following code to get it to display right:
    comment_author_IP); ?>" src="/flag/.gif" />

    thanks for the awesome plugin:)>-

  19. Hey,

    Well this worked for me:

    PHPMYADMIN > SQL Tab > Insert data from a text file into the table > DATA LOCAL LOAD method

    Take Care,
    Will

  20. ok Like this :d :

    LOAD DATA LOCAL INFILE ‘/path/to/ip-to-country.csv’ into table iptocountry fields terminated by ‘,’ enclosed by ‘”‘ lines terminated by ‘\r\n’;

  21. OK well, I had a couple of problems with the coding, but I fixed them and the plugin works great now. Thanks again! :)>-

  22. I used to have IP to Nation, and I must say it worked fine.
    The problem now is my provider! No matter what I use, it eill tell I am from Belgium… I am from Luxembourg!!! Might be a small country, but nonetheless… ahh… never mind, the plug-in works just fine on WP anyway!

    Thanks!

    賈偉柏

  23. :-w

    This plugin will not work for me. Followed instructions. comments.php cannot locate the functions from the activated plugin … Are the instructions lacking somewhere?

  24. Pingback: dhika@batikkejora
  25. I am a newbie in blogging… I am still puzzled how i install this IP to nation thingy? can anyone please give me a simple guide?

    elvin

  26. I already try the code that you provided but still unsuccesfull to used at my blog.. Pls elaborate more.

  27. Hi, I really like the comment boxes on this site! Is the “Using” line part of the ip-to-country-plugin?
    Also, being a PHP neo-newbie(like others) I can’t figure out how make the table ‘iptocountry’…
    Thanks!

  28. Nice Plugin! Hari ini saya coba pasang di website saya. Sempat beberapa jam utak-atik karena justru ip saya sendiri tidak ke-detect. Test sana sini menggunkana INET_ATON dan INET_NTOA di mysql baru ketemu kalau ip range saya tidak masuk database. Akhirnya saya insert manual dan sekarang sudah bisa muncul.

    Di website Mas Priyadi ini, sudah ke-detect, berarti databasenya sudah up-to-date. Apa ada script khusus yang otomatis memasukkan data baru ke database? Kalau ada, bagi-bagi dong ;)

  29. Hi,
    Does anyone here know about a CSV parser (free) becasuse I can’t get the SQL dump working or the CVS… Server does not alow import… But any way thanks…

  30. Hi, I was using the pluging v1.1 or something. Now with IP to Country version 2.0 and wordpress 2.0 also I get the following error:

    Parse error: parse error, unexpected ‘/’ in comments.php on line 43

    I follow the correct plugin installation procedure and I copy the following in my comments.php file.

    comment_author_IP); ?>” src=”/flag/flag-.gif”/>

    Any Sugestions? Thks in advance…

  31. maybe there is something wrong with the database or something. I installed this plugin. It’s great but my friend from Mauritius gets logged as being from China or Australia .

  32. I can’t for the life of me get it working. It keeps saying:

    Parse error: parse error, unexpected ‘/’ in /home/.fierce/kobrien/playground.pixelpolarity.com/wp-content/themes/k2/comments.php on line 62

    I think it refers to:

    <?php wp_ip2c_getCountryName(1,$comment<b/>-/>comment_author_IP); ?>

    Any help would be appriciated.

  33. Kok di saya flagnya gak bisa keluar ya? di taruhnya di plugin kan yah folder flagnya itu? di sini malah muncul nya kayak gini:
    … posted from Indonesia

  34. Just thought I’d share this ZIP file. It’s the SQL version of the CSV parse results (CSV from January 23 2006, the latest at the time of this comment).

    However, since phpMyAdmin times out in most cases when trying to process so many rows (over 67000), I’ve split it up into 10000 row parts. Simply upload each part, one at a time, and you should be good. :)

  35. #143: it is intentional. it is totally harmless and if I add ?>, it will generate unnecessary technical support load when people unintentionally add white space after it :)

  36. Om priyadi… saya punya kesulitan untuk masalah upload cvs itu,,,, jadi sampai sekarang saya masih pakai ip2country.. mohon petunjuk untuk newbie…

    satu lagi om.. kalo bisa sih adapting plugin ip2country dengan user online. jadi semua visitor yang ada keliatan benderanya.. tolong dong om :)

  37. Hi,
    I am using wordpress 2.0.2 (the one release on march 2006)
    I downloaded WordPress IP to Country Plugin (from priyadi.net), uploaded it to my Server and actived it from the blog admin control panel.
    I downloaded the SQL dump of IP to Country data (from Praveen website). From the Phpmyadmin I imported the sql file and the iptocountry was successully added as a table to my wordpress main database.
    I try all the Php Available functions in the sidebar, comments or index file but the plugin doesn´t work.
    Is there anything I didn´t do to make the Plugin work? Does the plugin work with the wordpress 2.0.2 version? If not, is there a way it can be customized or changed for wordpress 2.0.2.
    Can somebody helps!
    Thanks

    JC

  38. Yes, it works with 2.0.2, I’ve installed it on my blog and my wife’s blog. Just follow the instructions above to install, no extra steps needed.

  39. hey wait! i’m in Canada…how come it’s showing that I’m in the States? Anyway of forcing it to show Canada on my blog?

  40. Ok, so it does get my country but how come I don’t see no green, white, green. Priyadi, please hook a brother up with a decent Nigerian flag.

    It’d be cool if you include it in the next version of the plugin

  41. Hey, I went to the site to download the flags, but the link doesn’t work :(( , where else can I get the flags, please email them to me, I would appreciate it Thanks! :)>-

  42. I’m currently getting it integrated into my blog, but I’m getting problems with it… anyway, just testing here. ~o)

  43. Pingback: Gretong
  44. Probando, hay actualizaciones para la versión 2.1 de WordPress? a mi no me aparecen las banderas ultimamente U_U eso nunca me había pasado.

  45. Wah Priyadi jenius sekali kamu bisa bikin plugin kayak begini, :-? Om Pri ajarin dong bikin plugin wordpress, i Like this plugin so much… :d

  46. keren. gw noob lagi nyoba pasang boleh ya… btw itu kok bs ada nama kotanya sih?? ada yg perlu ditambah?

  47. Ah, how can I add city or something like in this code?

    eg: Hanoi, Taipei…

    Thank you.

  48. if you want to see city just add the following code into your comments.php file where you want (-;

    comment_author_IP;
    $contents = file_get_contents($file);
    $city = explode(',', $contents);
    echo $city[0];
    ?>

  49. english:

    in just a little while, i will released a wordpress plugin to translate commenters’s ip address to their city and country. so, please always monitoring my blog @ http://aufklarung.org

    indonesia:

    tidak lama dari sekarang, saya akan merilis sebuah wordpress plugin untuk mendeteksi kota dan negara dari para komenter. tingkat akurasi deteksinya tidak terlalu mengecewakan. jadi silahkan panatu terus blog sayah di http://aufklarung.org :D

    love
    -stanch

  50. PLS. DELETE MY EARLIER COMMENT!

    wow, this works and this is the coolest i’ve ever seen in blogging!

    hooray to you! added u to my rss feed:)

    Anyway, since i’m a newbie to WP, can you pls. spoonfed me the gruesome details of these:

    i have no idea HOW to create a table, or populate one, but if you can tell me what software(or notepad,etc..) can i do that, then i may have to start something.

  51. Test From Indonesia :)
    To Riri Audiya: Just Import the CSV file using PHPMyAdmin and it will be convert automatically

  52. i’m using WP 2.5.1..It seems to not work. i installed latest csv file to database+plus the tables of course.. followed every instruction to the letter.i see the plugin in my plugins too, activated it. but i don’t see it anywhere i’ve looked in settings WP admin page, manage,comments, etc, no such wp-ip2country dashboard. so i just added to the comment loop the above,php script, it still do not work..i only see the added php script in TEXT on my commenters..if you only made the setup clearer and the post updated, you could make tons of adsense revenue from this post alone. look at the number of commenters.pls. fix this or update plugin..we are counting on you.You could be the Pride of Indonesia if you just do what you do

  53. Have to agree with #230 above. I’m trying to get this to work with the Amazon Machine Tags plugin, but nothing seems to work. I’m using WP 2.6. I can’t get the plugin to work on comments either, as I’m not sure where in the comments loop it should go.

    I’ve added the latest CSV file to the database table and have activated the plugin. The installation of this was a real headache compared to other plugins (I’m not all that experienced with MySQL).

    If you can simplify the installation and make it idiot-proof, with clear and concise documentation, you’d be on to a winner. I’m happy for the people that found it easy, though.

Leave a comment

Your email address will not be published. Required fields are marked *