根据语言重定向用户

时间:2012-05-04 17:03:29

标签: php redirect

我有以下代码:

<?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/
< p>

如何将其实现到现有代码中?提前致谢! - 弗雷德里克安德森

修改

类似的解决方案;

$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();
}

3 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:2)

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

答案 2 :(得分:0)

这个怎么样

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

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

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

    header('Location: ' . $link);