Skip to content

Commit

Permalink
Add support for HTTP Accept-Language
Browse files Browse the repository at this point in the history
Allows site to auto-detect language based on HTTP Accept-Language header.

Uses a lightly modified version of the parser from
http://www.thefutureoftheweb.com/blog/use-accept-language-header.

Also cleans up unnecessary direct use of $_COOKIE and $_GET, which
are both covered by $_REQUEST, and uses a single language fallback
instead of a default + fallback.
  • Loading branch information
csnover committed Apr 23, 2016
1 parent 434f901 commit 25887c4
Showing 1 changed file with 41 additions and 11 deletions.
52 changes: 41 additions & 11 deletions index.php
Expand Up @@ -3,17 +3,47 @@
* Multilingual support
*/
global $lang;
/* Default to English */
$lang = 'en';
/* Check if the user has set a language preference before (cookies) */
if (!empty($_COOKIE['lang']))
$lang = $_COOKIE['lang'];
/* The GET language parameter should override any stored setting */
if (!empty($_GET['lang']))
$lang = $_GET['lang'];
/* Make sure that the language is known, otherwise fall back to English */
if (!preg_match("/^([a-z][a-z]|[a-z][a-z]_[a-z][a-z][a-z]?)$/", $lang))
$lang = "en";

$available_languages = array(
'en' => true,
'de' => true,
'fr' => true,
'it' => true,
'ru' => true
);

function get_preferred_languages() {
$lang_parse = array();
preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

if (count($lang_parse[1])) {
$langs = array_combine($lang_parse[1], $lang_parse[4]);
foreach ($langs as $candidate => $quality) {
if ($quality === '') {
$langs[$candidate] = 1;
}
}
arsort($langs, SORT_NUMERIC);
return array_keys($langs);
}

return array();
}

if (!empty($_REQUEST['lang'])) {
$lang = $_REQUEST['lang'];
} elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach (get_preferred_languages() as $candidate) {
$candidate_major = current(explode('-', $candidate, 1));
if (isset($available_languages[$candidate_major])) {
$lang = $candidate_major;
break;
}
}
}

if (!array_key_exists($lang, $available_languages))
$lang = 'en';

/* We have to clean the mess introduced by double cookie at the wrong level */
if (empty($_COOKIE['clear_lang'])) {
Expand Down

0 comments on commit 25887c4

Please sign in to comment.