PHP Language Detection

Sharing is caring!

We are searching for a modest route to immediately distinguish a clients dialect utilizing Php and went over this fascinating scrap which does simply that. It utilizes the Php superglobal “Http_accept_language” which returns something like this for me “en-Us,en;q=0.8″. This is the substance dialect code of the header from the present solicitation, if there is one.

The Php Code

This code essentially discovers what dialect header is situated (if there is one) and redirects the client to the applicable subdomain. English talking clients get re-controlled to en.mysite.com and so forth. In the variable $site we’re constructing an exhibit of every last one of dialects and subdomains backed. This implies that down the line in the event that you need to include more back for diverse dialects case in point German “de” you could just affix a quality and key to the $sites cluster.

the $lang variable takes our Php superglobal “Http_accept_language” and you’ll perceive that this is wrapped in the Php capacity substr(); which takes 3 parameters. The string, which for our situation is $_server[‘http_accept_language’]; we then tag the begin and the length qualities. So as we need to return and match just the first two characters of the string we determine 0,2.

The next section of code is an if statement that basically says if the language code doesn’t exist in the array then we either don’t support that language or a language code wasn’t set so it defaults to ‘en’.

We then redirect the page to the correct subdomain.

<?php // List of available localised versions as ‘lang code’ =–> ‘url’ map
$sites = array(
“en” => “http://en.mysite.com/”,
“es” => “http://es.mysite.com/”,
“fr” => “http://fr.mysite.com/”,
);

// Get 2 char lang code
$lang = substr($_SERVER[‘HTTP_ACCEPT_LANGUAGE’], 0, 2);

// Set default language if a ‘$lang’ version of site is not available
if (!in_array($lang, array_keys($sites))){
$lang = ‘en’;
}
// Finally redirect to desired location
header(‘Location: ‘ . $sites[$lang]);

?>

One thought on “PHP Language Detection

Leave a Reply

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

Got Project on mind? Let's ConnectContact Us

Secured By miniOrange