Detect languages with PHP - Nicolas BAPTISTA

Detect languages with PHP

If you have a standard website with CMS such Drupal, WordPress, phpBB… You may want to detect language in some pages.
To do so, you can use the following PHP function :

$_SERVER['HTTP_ACCEPT_LANGUAGE']

You should create an array of all the accepted languages, for example let’s say it’s French, English, Portuguese and Russian :

$acceptLang = ['fr', 'en', 'pt', 'ru'];

Then, you can set a default language, usually English the universal language, and detect if it’s in the array. Which will give:

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$acceptLang = ['fr', 'en', 'pt', 'ru'];
$lang = in_array($lang, $acceptLang) ? $lang : 'en';

Finally, in your code, you can use the value of the $lang variable to change the value of your text according the the selected language.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments