"http://www.mysite.com/", ); // Get 2 char lang code -6ren">
gpt4 book ai didi

php - 根据语言重定向用户

转载 作者:行者123 更新时间:2023-12-04 18:22:04 26 4
gpt4 key购买 nike

我有以下代码:

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

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/"
);

不起作用,因为它在重定向时会产生循环错误 - 至少在 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();
}

最佳答案

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

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

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

要添加该 session 变量,您可以执行以下操作:
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();
}

关于php - 根据语言重定向用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com