phplocalizationhttp-accept-language

Getting a user's language in PHP


I am trying to do localization for a site I'm working on at the moment and am doing something like this:

if(!isset($_SESSION['lang'])){
    $_SESSION['lang'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}else if(isset($_GET['lang']) && !empty($_GET['lang'])){
    $_SESSION['lang'] = $_GET['lang'];
}

This is fine and works as expected, however, sometimes there is no value for $_SERVER['HTTP_ACCEPT_LANGUAGE'], after a quick test of visitors to our site approximately 20% actually have a value and 80% do not.

Is there a better way to detect a user's language?


Solution

  • As suggested I ended up falling back to English in an else statement if I cannot determine the language