Posted in PHP

How to Implement Country Based Redirection Using PHP

How to Implement Country Based Redirection Using PHP Posted on January 19, 2018Leave a comment

Deepanker Verma is the CEO of Techlomedia and a full time blogger. On this blog, he shares web design resources, SEO tips blog monetization tips.

Ip to country with PHP
Best WordPress Hosting

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 freegeoip.net 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.

Advertisement

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 geoplugin.com. They also have a similar easy to use API.

Hostip.info 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 Hostip.info 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 freegeoip.net on few of my projects and recommend the same. If you have any question to ask, you can always leave it in the comment.

advertisement

Deepanker Verma is the CEO of Techlomedia and a full time blogger. On this blog, he shares web design resources, SEO tips blog monetization tips.

Leave a Reply

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

%d bloggers like this: