2

我有以下代码:

<?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]);
?>

如果它是丹麦网站客户端,这会将用户重定向到该站点的丹麦 (da) 版本,这是主站点。这是极好的。

但是,我想,如果用户不是丹麦语,而是波兰语、德语等,它会将他们重定向到位于子域的网站的英文版本

http://en.mysite.com/

如何在现有代码中实现它?提前致谢!——弗雷德里克·安徒生

编辑

像这样的解决方案;

$sites = array(
    "da" => "http://www.mysite.com/",
    "en" => "http://en.mysite.com/"
);

不起作用,因为它在重定向时会产生循环错误 - 至少在 Google Chrome 中是这样。

编辑 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();
}
4

3 回答 3

2

您需要将默认选项添加到您的数组:

$sites = array(
    "da" => "http://www.mysite.com/",
    "en" => "http://en.mysite.com/"
);

编辑:如果您"http://en.mysite.com/"再次调用相同的代码,它将创建一个循环。显而易见的解决方案是不在那里调用此代码,但另一种解决方案是设置一个会话变量以指示语言选择已经发生。

要添加该会话变量,您可以执行以下操作:

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();
}
于 2012-05-04T17:05:17.897 回答
2
$sites = array(
    "da" => "http://www.mysite.com/",
    "en" => "http://en.mysite.com/"
);
于 2012-05-04T17:06:08.753 回答
0

这个怎么样

    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

    $sub_domain = ($lang == "da") ? "www" : "en";

    $link = "http://".$sub_domain.".mysite.com/";

    header('Location: ' . $link);
于 2012-05-04T17:19:18.713 回答