the problem:

I need to detect visitor's country from his IP so I can display specific code based on the user location (different ads, etc.) in my PHP website.

There is many different external services such as Ip-api.org which does this, but I want to do it internally on the server (it's faster).

The question:

How to do it? What do I need to install or what do google out?


Ideally with some open-source licence.

  • I am not sure if this can be done just using PHP code as you can detect IP using the code but to detect country you might need to use external services to return the country of that IP. – TopQnA Jul 22 '17 at 13:51
  • @Goyllo This is not "recommendations for software" but "seeking for solution". – Jasom Dotnet Jul 23 '17 at 7:03
  • Same to @StephenOstermiller – Jasom Dotnet Jul 23 '17 at 7:04
  • @TopQnA I'm not interested in solo PHP code, I'm interested in whatever I can install on the server and has some connection with PHP. – Jasom Dotnet Jul 23 '17 at 7:07
  • 1
    Using IP addresses to determine the country is a tad unreliable. You need to make sure visitors can override the country setting. PS: You can't use the country to determine language. PPS: Tourists are in the wrong country and speak the wrong language, so they may need to change things manually. Make sure they can. – Oskar Skog Jul 23 '17 at 23:04


This will give you a database of IP ranges and associated country. You can query this with PHP to find out the country for a given IP address.

Make sure you read the license conditions. You will also need to keep the data updated, as otherwise it will get less accurate over time.

Not the answer you're looking for? Browse other questions tagged or ask your own question.