OBJECTIVE
I’m trying to accomplish an automatic redirect depending on the users language. I have a fully working code for that:
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.fredrixdesign.com/",
"en" => "http://en.fredrixdesign.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]);
?>
This redirects the user to a Danish (da) version, which is the main/root website, if the user is Danish. If the user is German, English, Polish, etc. it redirects the user to a subdomain; en.fredrixdesign.com, which is an English version of the website.
But the problem occurs, when a Danish-user goes on my site. The code, located in the top of my header.php, keep getting executed, which means, it keeps creating the redirect, which finally forces the browser to create an error due to too many redirects. This makes sence.
QUESTION
My question is then; how would I go around modifying the above code, so it only executes the redirect once? If it just completed the redirect, it will simply continue to execute the site.
Well, I bet you can find a solution yourself if just think it over a bit.
All you need is to check if current domain meets desired language.
Just amend your array a bit
and then add a condition for the redirect
that’s all