Simplest way to detect client locale in PHP

PHP provides a function beginning from 5.3.0 to parse the ‘$_SERVER['HTTP_ACCEPT_LANGUAGE']’ variable into a locale −


$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;

The ‘$_SERVER['HTTP_ACCEPT_LANGUAGE']’ function helps detect the locale by taking the current locale’s language as the parameter.


This will produce the following output −


Most browsers submit an Accept-Language HTTP header that specifies en-us if they are from the US. Some older browsers use en only.

English-UK based users usually set their system or user locale to English-UK, which is the default browser configuration. This would result in en-gb as the Accept Language header. Other countries have en locales, such as en-za (South Africa), and so on.

Geo-IP based guesses would less likely be correct on the preferred language/locale.