The following code will be able to detect default client’s browser language. I have tested this code by using Mozilla Firefox (FF) version 3.5.2 and Internet Explorer (IE) version 8browser. Both of those browsers worked like a charm! If you want to try using FF browser, go to the menu on that browser: Tools -> Options… -> Content -> Languages, then click on Choose… button. Add some languages as many as you need to the list afterwards. Try to change the position the language you want, by selecting the language first, and click the Move Up button to make it at the top of the list. Then run the following code, and you will see the output of the code is the language code that you have choosen before.
To make this code running, simply create a new file named detectbrowserlanguage.php. Copy-paste the following code below to that file and save the file. Put the file onto the root directory of your web server. Then run or call this file via your browser, for example: http://www.yourdoimain.com/detectbrowserlanguage.php.
Each time after you change the language at the first position on the list, then try to run again the code above via browser. You should see the result is the same language code with the one you have just changed before. This code sometimes you need when you want to make the different handling for the certain language according to the browser’s client when they access your website.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php $prefered_languages = array(); if(preg_match_all("#([^;,]+)(;[^,0-9]*([0-9\.]+)[^,]*)?#i", $_SERVER["HTTP_ACCEPT_LANGUAGE"], $matches, PREG_SET_ORDER)) { $priority = 1.0; foreach($matches as $match) { if(!isset($match[3])) { $pr = $priority; $priority -= 0.001; } else { $pr = floatval($match[3]); } $prefered_languages[$match[1]] = $pr; } arsort($prefered_languages, SORT_NUMERIC); foreach($prefered_languages as $language => $priority) { echo "This browser using language code: ".$language; exit; } } ?> |
0 comments:
Post a Comment