Last Updated: February 25, 2016
·
2.25K
· pyrech

Internationalize your site : get / set the user language

Here is couple of functions which allows you to make an internationalized app.

The first function returns the language, according to the user browser's configuration. Use it when your app start. After your called this function, your just have to display content in the correct language.

public function getLanguage() {
    $selected = 'en';
    $cookie_name = 'locale';
    // Locales available for your app
    $app_langs =array('en', 'fr', 'de');
    // If a locale was setted before and if is correct, we use it
    if (isset($_COOKIE[$cookie_name] && in_array($selected, $app_langs)) {
        $selected =$_COOKIE[$cookie_name];
    }
    // else let's go to determining the user locale
    else {
        // Parsing the HTTP_ACCEPT_LANGUAGE header
        $accepted_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        foreach($accepted_langs as $lang) {
            // Extract the language code
            $lang = strtolower(substr($lang, 0, 2));
            // If the lang exists and if available, let's use it
            if (in_array($lang, $app_langs)) {
                $selected = $lang;
                break;
           }
      }
      // Storage of the language wich will be used
      setLanguage($selected);
    }
    return $selected;
}

The second function allows you to set the language, e.g when the user wants to change the language of your app. If you use MVC design pattern, this function can be called from a particuliar controller, then redirect on your home page in the correct language.

public function setLanguage($lang) {
    $cookie_name = 'locale';
    setcookie($cookie_name, $lang, time()+60*60, '', '', false, true);
}