Reputation: 304
I have the following code:
<?php
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.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]);
?>
This will redirect the user to the Danish (da) version of the site, which is the main site, if it's a Danish website client. This is excellent.
But, I want, if the user isn't Danish, but Polish, German, etc. it redirects them to the English version of the site, which is located at the subdomain
http://en.mysite.com/
How do I implement that into the existing code? Thanks in advance! - Frederick Andersen
EDIT
A solution like;
$sites = array(
"da" => "http://www.mysite.com/",
"en" => "http://en.mysite.com/"
);
Doesn't work since it creates a loop error when redirecting - at least in Google Chrome.
EDIT 2
session_start();
if (isset( $_SESSION['redirect']))
{
// do nothing / continue with rest of page
}
else
{
$_SESSION['redirect'] = true;
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
"da" => "http://www.mysite.com/",
"en" => "http://en.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]);
exit();
}
Upvotes: 2
Views: 743
Reputation: 91734
You would need to add the default option to your array:
$sites = array(
"da" => "http://www.mysite.com/",
"en" => "http://en.mysite.com/"
);
Edit: If you are calling this same code in "http://en.mysite.com/"
again, it will create a loop. The obvious solution would be to not call this code there, but an alternative solution would be to set a session variable to indicate that the language selection has already taken place.
To add that session variable you could do something like:
session_start();
if (isset( $_SESSION['redirect']))
{
// do nothing / continue with rest of page
}
else
{
$_SESSION['redirect'] = true;
// your language selection code with header call
exit();
}
Upvotes: 2
Reputation: 6192
how about this
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$sub_domain = ($lang == "da") ? "www" : "en";
$link = "http://".$sub_domain.".mysite.com/";
header('Location: ' . $link);
Upvotes: 0
Reputation:
$sites = array(
"da" => "http://www.mysite.com/",
"en" => "http://en.mysite.com/"
);
Upvotes: 2