I would add an array with supported languages and check this with the post.
If there is no match change to some default language:
$languages = new stdClass();
$languages->default = 'en';
$languages->list = array('en', 'de', 'fr', 'es');
if (!empty($_POST['lang']) && in_array($_POST['lang'], $languages->list)) {
$Lang = $_POST['lang'];
$_SESSION['lang']= $_POST['lang'];
} else {
if (!empty($_SESSION['lang'])) {
$Lang = $_SESSION['lang'];
else
$Lang = get_browser_language($languages->list);
}
if (!in_array($Lang, $languages->list)) {
$Lang = $languages->default;
}
$_SESSION['lang'] = $Lang;
}
// I always use the following function to get the browser language (don't know anymore where I found it on the web)
function get_browser_language($available_languages,$http_accept_language='auto')
{
if ($http_accept_language == 'auto') $http_accept_language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$pattern = '/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?(\s*;\s*q\s*=\s*(1\.0{0,3}|0\.\d{0,3}))?\s*(,|$)/i';
preg_match_all($pattern, $http_accept_language, $hits, PREG_SET_ORDER);
$bestlang = $available_languages[0];
$bestqval = 0;
foreach ($hits as $arr) {
$langprefix = strtolower ($arr[1]);
if (!empty($arr[3])) {
$langrange = strtolower ($arr[3]);
$language = $langprefix . "-" . $langrange;
}
else $language = $langprefix;
$qvalue = 1.0;
if (!empty($arr[5])) $qvalue = floatval($arr[5]);
// find q-maximal language
if (in_array($language,$available_languages) && ($qvalue > $bestqval)) {
$bestlang = $language;
$bestqval = $qvalue;
}
// if no direct hit, try the prefix only but decrease q-value by 10% (as http_negotiate_language does)
else if (in_array($langprefix,$available_languages) && (($qvalue*0.9) > $bestqval)) {
$bestlang = $langprefix;
$bestqval = $qvalue*0.9;
}
}
return $bestlang;
}
You could also add an extra check based on a translation table from ip to country by using for example the data of: http://www.ip2nation.com/
Or perhaps even use GEO location to get the info. Although this would not be my preferred way since users will / should get a warning stating that the site tries to use GEO location of the visitor. If I see that I never accept although it may just be me :)
I would also have created a cookie with the user's preferred language, so that when the user visits the site again at a later time he/she doesn't have to select the language again.
$_SERVER['HTTP_ACCEPT_LANGUAGE']
might not be set. \$\endgroup\$