How to Implement Country Based Redirection Using PHP


If you are working on a website that has different content for different country, you must be thinking of implementing country based redirection. There could be lots of ways of doing this. You can use .htaccess method by using the mod_geoip module. But what if you want to do this with PHP. In this case, you need the IP address to country database. If you have this, you can easily capture the IP address of the visitor, you can get the location and perform redirection.

But getting the IP address to the country database is also not an easy task. So, Here I have a better and easier way.

The website offers a free to use API and allows 15000 queries per hour by default. That is more than enough for a website with up to 3,00,000 views a day.

There is no need to register for using this api. If you have the IP address of the visitor, you just need to pass in API URL to get the country. Here is the code.

The API returns Time/zone, postal code, city, country, country_code, and region_name. So, you have enough data to use on your website. Now you have the country of the user. I used country code as I wanted to use it for redirection.


There are few other similar websites, but they never confirm the API usage limit. So, this solution is not just simple but also has good allowable rate that can even be used on a high traffic website.

Alternatively, you can also try They also have a similar easy to use API. also got something similar to try. But they offer you text result in place of JSON or XML data. So, you need to parse the text. Here is how to get a result.

I tested for several IP address and couldn’t find it worth to use. Most of the results were wrong. So, go with the solution I mentioned at first.

Final Words

I tried to give good options for getting the country from IP and then do redirection based on that. I personally use on few of my projects and recommend the same. If you have any question to ask, you can always leave it in the comment.


Written by Deepanker

Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.

Leave a Reply

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


Disk Partition Software for Windows

5 Free Disk Partition Software for Windows


How to check ‘Last Seen’ Status On Instagram