PHP language detection

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

<?php
  $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; 
      }, []);
    arsort($prefLocales);
    /*
    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.


Here's the script I used for a bi-lingual site. It is to be used as index.php of mysite.com. 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.

<?php
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
    "en" => "http://en.mysite.com/",
    "bn" => "http://bn.mysite.com/",
);

// 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]);
?>

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 :

var_dump($_SERVER['HTTP_ACCEPT_LANGUAGE']);

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 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][1].

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 !

Tags:

Php