Detect user language with PHP

This function uses php server variables to detect the “possible” language of the browser of the connected user. This let…

December 16, 2009

This function uses php server variables to detect the “possible” language of the browser of the connected user. This let you show information with the correct language.
Since the HTTP_ACCEPT_LANGUAGE variable contains many information there is some dirty job to do with regular expression to clean the variable and determine the most important value from the ones contained.
The HTTP_ACCEPT_LANGUAGE contains language and q factor. This “q factor” indicates the importance of the language. The bigger is q factor the most important is the language, so the function split the variable, detect q factor and sort to extract the most important.

function getUserLanguage() {
	$langs = array();
	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		// break up string into pieces (languages and q factors)
		preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i',
				$_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);
		if (count($lang_parse[1])) {
			// create a list like "en" => 0.8
			$langs = array_combine($lang_parse[1], $lang_parse[4]);
			// set default to 1 for any without q factor
			foreach ($langs as $lang => $val) {
				if ($val === '') $langs[$lang] = 1;
			}
			// sort list based on value	
			arsort($langs, SORT_NUMERIC);
		}
	}
	//extract most important (first)
	foreach ($langs as $lang => $val) { break; }
	//if complex language simplify it
	if (stristr($lang,"-")) {$tmp = explode("-",$lang); $lang = $tmp[0]; }
	return $lang;
}

Author

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Recommended

Count coloured cells on Google Sheets with reference

In a spreadsheet if you need to count cells based on their background you can use this code in Google…

May 22, 2020

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

February 8, 2020

Two post types share the same taxonomy in WordPress

Sharing a WordPress taxonomy between two post types is useful especially if you want to create a relation between different…

November 14, 2019

MYSQL add counter in a query

Use mysql variables to create a counter in SQL, PHP code to use an SQL counter and what does the i mean in mysqli?

November 9, 2019

Modify the language attribute based on category in WordPress

How to modify the language attribute in your Wordpress theme using a specific value

November 7, 2019

WordPress Fatal error: Unknown: Cannot use output buffering in output buffering display handlers in Unknown on line 0

How I've beat the php mysterious fatal error unknown in Wordpress caused by caching plugin WP Fastest Cache