Get web browser preferred language with PHP $_SERVER variables HTTP_ACCEPT_LANGUAGE

HTTP Language headers.
In php the way to get the language information sent by browser is with server reserved variables.

1
2
3
<?php
echo $_SERVER['HTTP_ACCEPT_LANGUAGE']);
?>

Which output (in my browsers):

  • ca,en-us;q=0.7,en;q=0.3 in Mozilla Firefox 13.0.1
  • es-ES in Internet Explorer 9 64b
  • ca-ES,ca;q=0.8 in Google Chrome 20.0

The “q-value” (when it’s shown in a value range between 0-1) indicates the percent that the browser prefer this language. If it’s not provided, we asume is 1 (maximum).

How to get the preferred language?
Here’s a simple function I’ve coded to get the preferred language according q-value in ISO 639-1 format:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
function GetLanguageCodeISO6391()
{
	$hi_code = "";
	$hi_quof = 0;
	$langs = explode(",",$_SERVER['HTTP_ACCEPT_LANGUAGE']);
	foreach($langs as $lang)
	{
		list($codelang,$quoficient) = explode(";",$lang);
		if($quoficient == NULL) $quoficient = 1;
		if($quoficient > $hi_quof)
		{
			$hi_code = substr($codelang,0,2);
			$hi_quof = $quoficient;
		}
	}
	return $hi_code;
}
 
echo "Your browser preferred language is: ".GetLanguageCodeISO6391();
?>

To check what will output in your browser, go to this demo.

 

Leave a Reply

Your email address will not be published. Required fields are marked *