Instead of (or at least in addition to) looking at country of the IP address, you should inspect Accept-Language
HTTP header ($_SERVER['HTTP_ACCEPT_LANGUAGE']
in PHP)
This header usually contains language-country pairs:
en-US, hi_IN, fr, de;q=0.5
PHP intl extension has methods that help parsing it.
Problems with IP lookup:
Normal users don't have ability to change their IP address or how their address is classified in IP-geo databases. It's much more likely that users are able to choose/configure language of their operating system/browser, which influences the Accept-Language
header.
There are ISP proxies that are in country different than the user, e.g. AOL routes some international traffic through US, many mobile users use Opera Mini which has proxy servers in Norway. If you're looking up IP, at least take X-Forwarded-For
header into account. Accept-Language
header is passed through proxies without such problems.
I've been using hostip.info database and found it to be incomplete and contain errors. Also consider that making HTTP request to a 3rd party PHP script each time is going to slow down your site and waste their resources. Parsing of Accept-Language
header is essentially free.
If you don't want merely country, but language users speaks, then IP→Country won't be accurate for countries where different languages are spoken. Accept-Language
may give you more precise information (e.g. nl_BE
for Dutch in Belgium, fr_CA
for Canadian French).
Neither method is 100% correct, so it would be wise to let users override your selection.
Also keep in mind that if you force redirects to "correct" domain then bots of search engines won't be able to index all your domains, as they will most likely come from an US IP address and won't specify preferred language. It's best not to apply detection to domains other than .com
, and/or don't apply it to pages other than the homepage.