How to decide user's language

与世无争的帅哥 提交于 2019-12-07 08:37:21

Taken from the MicroMVC framework. The following looks for a cookie that could be set by a Javascript language selector - and if it's not found it uses the setting the users browser sends.

// Get locale from user agent
if(isset($_COOKIE['lang']))
{
    $preference = $_COOKIE['lang'];
}
else
{
    $preference = Locale::acceptFromHttp(getenv('HTTP_ACCEPT_LANGUAGE'));
}

// Match preferred language to those available, defaulting to generic English
$locale = Locale::lookup(config()->languages, $preference, false, 'en');

// Default Locale
Locale::setDefault($locale);
setlocale(LC_ALL, $locale . '.utf-8');
//putenv("LC_ALL", $locale);

Requires PHP 5.3 and the ICU INTL library.

$ sudo apt-get install php5-intl
  1. Use the browser's language

  2. Provide an easily accessible menu to switch languages at all times.

Using Geolocation to set the first choice is an option as well, but it's not 100% reliable, and the actual browser language is a much better indicator of what language the user speaks.

Geo location will fail in many situations. For example an english speaking person on travel/vacation gets the wrong language presented while staying in Ukraine. I think most users have their correct language in the browser settings.

Get the browser's used language ($_SERVER['HTTP_USER_AGENT']) automatically but the provide a select box (or something else) to give the possibility to the user to select another language. If you are using a framework (and you should) it should have some helper method.

I would not use a GeoIP, say an US guy is browsing your site on holiday in France.

The best practice is to let your user decide their language from a selector.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!