Get IP Address of Country using PHP

Today, the internet is accessed from all around the world. There is a need for country specific content or more targeted ads. It is possible to get a country from an IP address.

IP address is a unique identifier for each PC accessing the internet. They are also grouped by country, so it is possible to identify a country by looking at an IP address.

There are three ways to do this in PHP:

1. Build a module into the PHP server

There is an extension on PHP called GeoIP that you can include in your build of PHP. This is an alternative if you own or have full access to your PHP server. If you are using shared web hosting, this does not apply. It does requires you to purchase a license from Maxmind, in order to utilize the extension. See the PHP Manual entry on Geo IP Location Extension. You may need to check the requirements page.

2. Import existing IP tables into the your own database

There are IP tables that you can import into your own database. However, you are responsible for updating the tables if new changes occurs. You can use Maxmind GeoIP Lite App or PHP Weby IP 2 Country Class.

3. Use existing API

There are numerous API you can use to help. Of course, should the API becomes out of date or unavailable, your system will fall apart. You are at the mercy of the API owner. Here are some API list you can use:

Do read the API terms carefully before using it.

I hope you find them useful.

References:

  1. IP Based Image thread on Webdeveloper
  2. Get Country of IP Address with PHP thread on Stack Overflow