PHP language detection-ThrowExceptions

Exception or error:

I’m trying to build multilangual site.

I use this piece of code to detect users language. If you havent chosen a language, it will include your language file based on HTTP_ACCEPT_LANGUAGE.

I don’t know where it gets it from though:


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

elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'en') $_SESSION['lang'] = "en";
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'sv') $_SESSION['lang'] = "sv";
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'pl') $_SESSION['lang'] = "pl";
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'fr') $_SESSION['lang'] = "fr";


It works for me and includes the polish lang file. But is this code accurate? Or is there another way?

How to solve:

The browser generally sends a HTTP header, name Accept-Language, that indicates which languages the user is willing to get.

For instance, this header can be :

Accept-Language: en-us,en;q=0.5

There is notion of priority in it, btw ­čśë

In PHP, you can get this in the $_SERVER super global :


will get me :

string 'en-us,en;q=0.5' (length=14)

Now, you have to parse that ­čśë

If I edit my preferences in the browser’s option to say “I want french, and if you don’t can’t serve me french, get me english from the US ; and if you can’t get me that either, just get me english), the header will be :

Accept-Language: fr-fr,en-us;q=0.7,en;q=0.3

And, from PHP :

string 'fr-fr,en-us;q=0.7,en;q=0.3' (length=26)

For more informations, you can take a look at section 14.4 of the HTTP RFC.

And you probably can find lots of code example in PHP to parse that header ; for instance : Parse Accept-Language to detect a user’s language

Have fun !


Here’s the script I used for a bi-lingual site. It is to be used as index.php of Based on the user’s browser’s language preference, it would redirect to desired language version of the site or the default language site if the site in user’s preferred langauge was not available.

// List of available localized versions as 'lang code' => 'url' map
$sites = array(
    "en" => "",
    "bn" => "",

// Get 2 char lang code
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

// Set default language if a `$lang` version of site is not available
if (!in_array($lang, array_keys($sites)))
    $lang = 'en';

// Finally redirect to desired location
header('Location: ' . $sites[$lang]);


I know there already many good solutions, but have found my own way to solve this problem.

  $prefLocales = array_reduce(
    explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']), 
      function ($res, $el) { 
        list($l, $q) = array_merge(explode(';q=', $el), [1]); 
        $res[$l] = (float) $q; 
        return $res; 
      }, []);
    This get you from headers like this
      string 'en-US,en;q=0.8,uk;q=0.6,ru;q=0.4' (length=32)
    array like this
    array (size=4)
      'en-US' => float 1
      'en' => float 0.8
      'uk' => float 0.6
      'ru' => float 0.4

Code will convert HTTP_ACCEPT_LANGUAGE string to array with locales as keys and weight as values, sorted from high value to low. So you can just get one by one with array_shift to get the best match with your site locales.


You can use: Locale::acceptFromHttp().

Tries to find locale that can satisfy the language list that is requested by the HTTP “Accept-Language” header.


Your code looks just fine. You might want to add a final else default choice if the visitor asks for a language you aren’t providing.
Also, if the visitor himself selects a language you should save that choice in a persistent cookie and check its value, giving it precedence over HTTP_ACCEPT_LANGUAGE.

As far as I can tell Youtube does use HTTP_ACCEPT_LANGUAGE, but at the same time uses IP geolocation to suggest a change in language if the langauge of the visitor’s country doesn’t match that. Definitely annoying.

Just nitpicking: if you’re gonna add languages to the list a switch() statement might be more readable.


Here’s a function for selecting the best out of a group of supported languages. It extracts languages from Accept-Language, then sorts the given array of languages according to their priority.

function select_best_language($languages) {
    if (!$_SERVER['HTTP_ACCEPT_LANGUAGE']) return $languages[0];
    foreach (explode(",",$_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lqpair) {
        if ($lq[1]) $lq[1]=floatval($lq[1]); else $lq[1]=$default_q--;
    usort($languages,function($a,$b) use ($larr) { return $larr[$b]<=>$larr[$a]; });
    return $languages[0];

$lang = select_best_language(['en','fr','it']);


Try This

function getUserLanguage() {
    $langs = array();

    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        // break up string into pieces (languages and q factors)

        if (count($lang_parse[1])) {
            // create a list like 'en' => 0.8
            $langs = array_combine($lang_parse[1], $lang_parse[4]);

            // set default to 1 for any without q factor
            foreach ($langs as $lang => $val) {
                if ($val === '') {
                    $langs[$lang] = 1;
            // sort list based on value
            arsort($langs, SORT_NUMERIC);
    //extract most important (first)
    $lang = key($langs);

    //if complex language simplify it
    if (stristr($lang, '-')) {
        list($lang) = explode('-', $lang);

    return $lang;


This is also possible. It will use english as default if .php is not available.

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
(@include_once 'languages/'.$lang.'.php') or (@include_once 'languages/en.php'); 



Leave a Reply

Your email address will not be published. Required fields are marked *