Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect user language in PHP - stable solution

Tags:

php

I'm currently working on a auto-user-language-detection for providing the content in the user's language.

of course its possible to change the language manually, but if a user visits the page for the first time I want to provide the content in his language.

So I was googling and found the $_SERVER['HTTP_ACCEPT_LANGUAGE']-Var to get a result like that:

de-de,de;q=0.8,en-us;q=0.5,en;q=0.3

whats the best way to filter this result to get a clear result like "EN" / "DE" / "IT"?

$rL = $_SERVER["HTTP_ACCEPT_LANGUAGE"]; //  de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
$langCode = strtoupper($rl[0].$rl[1]);

the second issue on this Server-Var is that its only give me a result if the browser provide some information. Is setting a default page language the only possibility to handle that?

The second possibility I'm interested in is to get the language by IP. So if I get the Language I probably know the language of the user. But whats in multi-language-countries like Switzerland, Belgium? Whats with tld's like .com / .net / .org and so on.

So which method would you apply to detect the users language?

thanks for helping.

like image 584
wildhaber Avatar asked Sep 29 '09 16:09

wildhaber


2 Answers

As a best practice, I will go with the really well developed Zend_Locale components from Zend Framework.

It have all what you need to I18n and localize your application, from detection of the user's local settings to the wide number of internationalized currency, number, date formating and translation management solutions.

like image 37
Shreef Avatar answered Nov 01 '22 06:11

Shreef


Stick with Accept-Language. All browsers pass the header and it's much more likely to be the language the user wanted than the crude guess of geolocation.

PECL has http_negotiate_language which can parse the header and choose a language for you properly, though in practice even the somewhat bogus method of just looking for en/de/it in the string works better than the IP sniffing.

Whats with tld's like .com / .net / .org and so on.

Domain names aren't usually involved in IP sniffing, which has its own backend database of IP ranges that are probably connected to some country. Reverse-resolution for country guessing is of almost no use as few IPs reverse-resolve to a ccTLD.

like image 142
bobince Avatar answered Nov 01 '22 04:11

bobince