Simplest way to detect client locale in PHP

PHPServer Side ProgrammingProgramming

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

Example

$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.

Output

This will produce the following output −

en_US

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.

raja
Published on 07-Apr-2020 11:51:05
Advertisements