I am developing a multilingual site, so i needed some sort of a function to detect user locale, as well as not to scare away search engines, so I wrote this kind of a method to detect locale. The priority is as following:
We look if user has active language in $_SESSION;
If not, we look in the database to detect user preference;
If nothing in the database, we look on the domain name and try to detect locale from domain name and superglobal $_SERVER;
If we failed, we look at user's browser locale ($_SERVER again) and try to detect from it.
If we are totally a failure, we fallback to English.
This method is called on every page of a website.
public static function detect_locale() {
if(isset($_SESSION["lang"])){
$lang = $_SESSION["lang"];
return $lang;
}
if(isset($_SESSION["id"])){
$user = new User($_SESSION["id"]);
$lang = $user->get_locale();
return $lang;
}
if($_SERVER["HTTP_HOST"] == "ru.mysupersite.com" || $_SERVER["HTTP_HOST"] == "www.mysupersite.ru"){
$lang = "ru";
return $lang;
}
if(isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])){
$lang = substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
return $lang;
}
$lang = "en";
return $lang;
}
I see it as a pretty straightforward solution, but something in the back of my mind says that there might be some flaws. Are there any or am I just paranoid?
Thank you!
$lang
and only return if it's accepted and otherwise fall through to the subsequent tests. I'd also move the language-from-host detection code to it's own function to allow for easier testing and extension. \$\endgroup\$