Find Browser Language

Snippets, useful things or other stuff here.

Moderators: ne_moj, zewa, vadimako, ne_moj, zewa, vadimako

paragate
Master
Master
Posts: 151
Joined: Nov 13th, '14, 13:04
Location: Denmark, Odense

Find Browser Language

Postby paragate » Oct 26th, '16, 07:57

This small snippet can be combined with apphp language selection, so that the chosen browser language is actually the language shown when visitors enters a webpage.
Any corrections to the snippet are welcome.

Code: Select all

   $str_browser_language = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? strtok(strip_tags($_SERVER['HTTP_ACCEPT_LANGUAGE']), ',') : '';
   $str_browser_language = !empty($_GET['language']) ? $_GET['language'] : $str_browser_language;
   switch (substr($str_browser_language, 0,2))
   {
      case 'de':
         $str_language = 'de';
         break;
      case 'da':
         $str_language = 'da';
         break;
      case 'en':
         $str_language = 'en';
         break;
      default:
         $str_language = 'en';
   }
   
   $arr_available_languages = array();
   $arr_available_languages[] = array('str_name' => 'English', 'str_token' => 'en');
   $arr_available_languages[] = array('str_name' => 'Deutsch', 'str_token' => 'de');
   $arr_available_languages[] = array('str_name' => 'Dansk',   'str_token' => 'da');
   
   $str_available_languages = (string) '';
   foreach ($arr_available_languages as $arr_language)
   {
      if ($arr_language['str_token'] !== $str_language)
      {
         $str_available_languages .= '<a href="'.strip_tags($_SERVER['PHP_SELF']).'?language='.$arr_language['str_token'].'" lang="'.$arr_language['str_token'].'" xml:lang="'.$arr_language['str_token'].'" hreflang="'.$arr_language['str_token'].'">'.$arr_language['str_name'].'</a> | ';
      }
   }
   $str_available_languages = substr($str_available_languages, 0, -3);
?>

Return to “Snippets, Tutorials & Other Stuff”