Coder Perfect

In PHP, you can detect the browser language.


For my website’s index, I use the PHP script below.

Depending on the browser’s language, this script should include a specified page (automatically detected).

Because this script does not operate with all browsers, it always includes index en.php for every language that is recognized (the cause of the problem is most probably an issue with some Accept-Language header not being considered).

Could you possibly recommend a more reliable solution?

// Open session var
// views: 1 = first visit; >1 = second visit

// Detect language from user agent browser
function lixlpixel_get_env_var($Var)
         $GLOBALS['_SERVER'][$Var] : (!empty($GLOBALS['HTTP_SERVER_VARS'][$Var])) ? $GLOBALS['HTTP_SERVER_VARS'][$Var]:'';

function lixlpixel_detect_lang()


     // Try to detect Primary language if several languages are accepted.
     foreach($GLOBALS['_LANG'] as $K)
         if(strpos($_AL, $K)===0)
         return $K;

     // Try to detect any language if not yet detected.
     foreach($GLOBALS['_LANG'] as $K)
         if(strpos($_AL, $K)!==false)
         return $K;
     foreach($GLOBALS['_LANG'] as $K)
         //if(preg_match("/[[( ]{$K}[;,_-)]/",$_UA)) // matching other letters (create an error for seo spyder)
         return $K;

     // Return default language if language is not yet detected.
     return $GLOBALS['_DLANG'];

// Define default language.

// Define all available languages.
// WARNING: uncomment all available languages

$GLOBALS['_LANG'] = array(
'af', // afrikaans.
'ar', // arabic.
'bg', // bulgarian.
'ca', // catalan.
'cs', // czech.
'da', // danish.
'de', // german.
'el', // greek.
'en', // english.
'es', // spanish.
'et', // estonian.
'fi', // finnish.
'fr', // french.
'gl', // galician.
'he', // hebrew.
'hi', // hindi.
'hr', // croatian.
'hu', // hungarian.
'id', // indonesian.
'it', // italian.
'ja', // japanese.
'ko', // korean.
'ka', // georgian.
'lt', // lithuanian.
'lv', // latvian.
'ms', // malay.
'nl', // dutch.
'no', // norwegian.
'pl', // polish.
'pt', // portuguese.
'ro', // romanian.
'ru', // russian.
'sk', // slovak.
'sl', // slovenian.
'sq', // albanian.
'sr', // serbian.
'sv', // swedish.
'th', // thai.
'tr', // turkish.
'uk', // ukrainian.
'zh' // chinese.

// Redirect to the correct location.
// Example Implementation aff var lang to name file
echo 'The Language detected is: '.lixlpixel_detect_lang(); // For Demonstration
echo "<br />";    
$lang_var = lixlpixel_detect_lang(); //insert lang var system in a new var for conditional statement
echo "<br />";    

echo $lang_var; // print var for trace

echo "<br />";    
// Insert the right page iacoording with the language in the browser
switch ($lang_var){
    case "fr":
        //echo "PAGE DE";
        include("index_fr.php");//include check session DE
    case "it":
        //echo "PAGE IT";
    case "en":
        //echo "PAGE EN";
        //echo "PAGE EN - Setting Default";
        include("index_en.php");//include EN in all other cases of different lang detection

Asked by GibboK

Solution #1

Why don’t you keep it basic and straightforward?

    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    $acceptLang = ['fr', 'it', 'en']; 
    $lang = in_array($lang, $acceptLang) ? $lang : 'en';
    require_once "index_{$lang}.php"; 


Answered by Pramendra Gupta

Solution #2

Accept-Language is a weighted list of variables (see q parameter). That means that simply looking at the first language does not imply that it is also the most preferred; in fact, a q score of 0 indicates that the language is completely unacceptable.

Rather than focusing solely on the first language, examine the list of accepted and available languages to discover the greatest match:

// parse list of comma separated language tags and sort it by the quality value
function parseLanguageList($languageList) {
    if (is_null($languageList)) {
        if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            return array();
        $languageList = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
    $languages = array();
    $languageRanges = explode(',', trim($languageList));
    foreach ($languageRanges as $languageRange) {
        if (preg_match('/(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?/', trim($languageRange), $match)) {
            if (!isset($match[2])) {
                $match[2] = '1.0';
            } else {
                $match[2] = (string) floatval($match[2]);
            if (!isset($languages[$match[2]])) {
                $languages[$match[2]] = array();
            $languages[$match[2]][] = strtolower($match[1]);
    return $languages;

// compare two parsed arrays of language tags and find the matches
function findMatches($accepted, $available) {
    $matches = array();
    $any = false;
    foreach ($accepted as $acceptedQuality => $acceptedValues) {
        $acceptedQuality = floatval($acceptedQuality);
        if ($acceptedQuality === 0.0) continue;
        foreach ($available as $availableQuality => $availableValues) {
            $availableQuality = floatval($availableQuality);
            if ($availableQuality === 0.0) continue;
            foreach ($acceptedValues as $acceptedValue) {
                if ($acceptedValue === '*') {
                    $any = true;
                foreach ($availableValues as $availableValue) {
                    $matchingGrade = matchLanguage($acceptedValue, $availableValue);
                    if ($matchingGrade > 0) {
                        $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
                        if (!isset($matches[$q])) {
                            $matches[$q] = array();
                        if (!in_array($availableValue, $matches[$q])) {
                            $matches[$q][] = $availableValue;
    if (count($matches) === 0 && $any) {
        $matches = $available;
    return $matches;

// compare two language tags and distinguish the degree of matching
function matchLanguage($a, $b) {
    $a = explode('-', $a);
    $b = explode('-', $b);
    for ($i=0, $n=min(count($a), count($b)); $i<$n; $i++) {
        if ($a[$i] !== $b[$i]) break;
    return $i === 0 ? 0 : (float) $i / count($a);

$accepted = parseLanguageList($_SERVER['HTTP_ACCEPT_LANGUAGE']);
$available = parseLanguageList('en, fr, it');
$matches = findMatches($accepted, $available);

If findMatches returns an empty array, no match was discovered, and the default language can be used instead.

Answered by Gumbo

Solution #3

I built this smaller, auto-matching version because the old replies are a little too verbose.

function prefered_language(array $available_languages, $http_accept_language) {

    $available_languages = array_flip($available_languages);

    preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER);
    foreach($matches as $match) {

        list($a, $b) = explode('-', $match[1]) + array('', '');
        $value = isset($match[2]) ? (float) $match[2] : 1.0;

        if(isset($available_languages[$match[1]])) {
            $langs[$match[1]] = $value;

        if(isset($available_languages[$a])) {
            $langs[$a] = $value - 0.1;


    return $langs;

And here’s an example of how to use it:

//$_SERVER["HTTP_ACCEPT_LANGUAGE"] = 'en-us,en;q=0.8,es-cl;q=0.5,zh-cn;q=0.3';

// Languages we support
$available_languages = array("en", "zh-cn", "es");

$langs = prefered_language($available_languages, $_SERVER["HTTP_ACCEPT_LANGUAGE"]);

/* Result
    [en] => 0.8
    [es] => 0.4
    [zh-cn] => 0.3

Here’s where you can get the whole gist.

Answered by Xeoncross

Solution #4

The PECL HTTP library is the approved way to handle this. Unlike some other replies, this one appropriately respects language priority (q-values), incomplete language matches, and returns the closest match, or the first language in your array if none are found.


How to use:

$supportedLanguages = [
    'en-US', // first one is the default/fallback

// Returns the negotiated language 
// or the default language (i.e. first array entry) if none match.
$language = http_negotiate_language($supportedLanguages, $result);

Answered by diggersworld

Solution #5

The difficulty with the selected response is that the user’s first language choice may be one that isn’t in the case structure, but one of their other language choices is. You should repeat this process until you locate a match.

This is a really basic solution that is more effective. Because browsers return languages in order of choice, the situation is simplified. Although the language designator can include more than two characters (for example, “EN-US”), the first two are usually adequate. In the code below, I’m seeking for a match from a list of languages that my application recognizes.

$known_langs = array('en','fr','de','es');
$user_pref_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);

foreach($user_pref_langs as $idx => $lang) {
    $lang = substr($lang, 0, 2);
    if (in_array($lang, $known_langs)) {
        echo "Preferred language is $lang";

I hope you find this to be a quick and easy solution that you can incorporate into your code. This is something I’ve been using in production for quite some time.

Answered by Darryl

Post is based on