设置一个cookie来保存用户的语言选择,并被重定向到所选页面而不是主页


Set a cookie to save users language choice and get redirected to the selected page instead of the home page

我正在制作一个区域选择器,允许用户选择他们想要查看我们网站的区域/语言。我卡住的部分是试图有一个cookie到位,以便一旦用户选择一个地区(例如中国),每当他们试图再次访问家庭域时,他们将自动重定向到他们以前选择的地区。

有可能需要一些帮助来开始吗?

Javascript方式

你可以使用localStorage。

如何重定向用户

在你的javascript文件中添加这个

// Test if localStorage is supported by the user's browser
if (typeof(Storage) !== "undefined") {
  var countryCode = localStorage.getItem("countryCode");
  if (countryCode) {
    window.location.href = 'http://www.your-website.com/' + countryCode;
  }
}

如何设置localStorage

首先,您必须监听select元素上的更改事件。

document.getElementById("yourSelect").addEventListener("change", setNewRegion);
然后,设置你的localStorage (我假设你的选项值是国家代码)
function setNewRegion(e) {
  // Get the selected value
  var countryCode = e.target.value;
  // Test if localStorage is supported by the user's browser
  if (typeof(Storage) !== "undefined") {
    // localStorage is available
    localStorage.setItem("countryCode", countryCode);
  }
  // ... Then redirect ?
}

我建议创建一个函数来测试localStorage是否被支持一次,并将结果存储在一个全局变量中。

希望对您有所帮助

您应该能够在服务器端或客户端执行此操作。我认为服务器端是更好的方式。当主页被击中,你会首先检查lang cookie,如果设置重定向到正确的特定于lang的主页。应该是相当直接的。

就像这样。或者使用switch语句,如果你有很多语言

if($_COOKIE['lang'] === 'CHN') {
header('Location: /chn/index.php');
}

首先,您必须确定cookie是否已经设置,如果它们是:重定向。如果没有:如果表单被提交,设置cookie

if( isset($_COOKIE['lang']) && !empty($_COOKIE['lang']) ){
     header('Location: /path/to/' . $_COOKIE['lang'] . '/');
}elseif( isset($_GET['lang']) && !empty($_GET['lang']) ){
    $_COOKIE['lang'] = $_GET['lang'];
    //Or you could use this method(preffered)
    //setcookie(name, value, expire);
    setcookie("lang", $_GET['lang'], ( time() + (60*60*24*365*2) ) );
}

过期时间的转换:

time() + (60*n)  =>,n分钟
time() + (60*60*n),=>,n个小时
time() + (60*60*24*n),=>,n天
time() + (60*60*24*365*n),=>,n年