Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect web browser language using PHP

Tags:

php

I found that there are a different responses for this code for every language, depend on lot of factors.

$lang = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $lang;  

for example English language : en_EN,en-EN,en_GB,en_US,en-GB,en-US. the same for French and other languages. what i'm looking for is where can i find those lang synonym so i can provide the right page language for every one of them.
for now i have a 3 language, so what i'm looking for is to find all possibilities for English language and French language and Arabic language something like this:

if (($lang=="en_EN") OR ($lang=="en-EN") OR ($lang=="en_GB") OR ($lang=="en_US") OR ($lang=="en-GB") OR ($lang=="en-US"))  {
    echo 'show English version';
}else if (($lang=="fr_FR")  ...... )  { // i don't know the other like fr-FR .....
    echo 'show French version';
}else if (($lang=="ar_AR")  ...... )  { // i don't know the other like ar-AR .....
    echo 'show Arabic version';
}else {
    echo 'English as default';
}
like image 248
ler Avatar asked Dec 13 '22 20:12

ler


2 Answers

Based on your example, it seems that you're not concerned with the language localisation (if it's British English or American English for example). Rather you're only concerned that the language preference is English.

That being the case, I would suggest taking only the first two characters from the locale.

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

This will return you en, fr, ar, etc, irrespective of the localisation. Use this to set the content language that is returned to the user, and if a language doesn't exist, server a default language, e.g. English.

like image 76
fubar Avatar answered Dec 30 '22 18:12

fubar


switch (substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2))
{
    case 'ar': break; # Arabic
    case 'fr': break; # France
    default:   break; # English
}

You are able to improve this realization: $_SERVER['HTTP_ACCEPT_LANGUAGE'] may have ; separated values, than means that user is able to read some langs per 1 time, so you can check all of them if you want to know what you may offer to him from your list.

like image 45
user1597430 Avatar answered Dec 30 '22 18:12

user1597430