kaldung.com

the website of roy kaldung

 

detect your user's preferred language

The easiest way to gain information about the user's language is to use available headers from the browser at the webserver. The relevant request header Accept-Language is available in PHP through the $_SERVER array and described in the RFC 2616. I'm using a quick and dirty script, but for my purpose it works well - at the moment.

I use it to redirect the browser to my english or german website, whereas the first match wins. The browser sends a header like: Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 Each language code is seperated by each other with a comma. The information after the semicolon is ignored by the script, for a detailed description see the RFC.


  1 : <?php
  2 : /**
  3 :  * detect the preferred language of the user agent
  4 :  *
  5 :  * @copyright Roy Kaldung <roy@kaldung.com>
  6 :  * @license http://www.php.net/license/3_01.txt PHP license
  7 :  */
  8 : 
  9 : /**
 10 :  * split request header Accept-Language to switch
 11 :  * between english and german, default is english
 12 :  *
 13 :  * @param string $defaultlang preselected language, default en
 14 :  * @return string returns 'de' or 'en'
 15 :  */
 16 : function detectLanguage($defaultlang = 'en') 
 17 : {
 18 :     $langlist = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
 19 :     $lang = $defaultlang;
 20 :     foreach($langlist as $curLang) {
 21 :         $curLang = explode(';', $curLang);
 22 :         /* use regular expression for language detection */
 23 :         if (preg_match('/(en|de)-?.*/', $curLang[0], $reg)) {
 24 :             $lang = $reg[1];
 25 :             break;
 26 :         }
 27 :     }
 28 :     return $lang;
 29 : }
 30 : ?>
© 2003-2011 Roy Kaldung • contact imprint technical information privacy
last modification:  2006-12-14 22:06 CET
Valid XHTML 1.0 Strict Valid CSS! ipv6 ready