设置cookie以保存用户语言选择并重定向到所选页面而不是主页[关闭]

I am in the process of making a region selector to allow users to select what region/language they would want to view our website in. The part I am stuck at is trying to have a cookie be in place so that as soon a user selects a region (China for example) whenever they try to access the home domain again, they will automatically get redirected to the region they have previously chosen before.

Would it be possible to have some assistance to get started?

You should be able to do this either server side or client side. I would think server side would be a better way of doing it. When homepage is hit you would first check for lang cookie and if set redirect them to the correct lang specific homepage. Should be fairly straight forward.

Something like this. Or use a switch statement if you have a lot of languages

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

Javascript way

You can do this with localStorage.

How to redirect user

On your javascript file, add this

// 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;
  }
}

How to set the localStorage

First, you must listen the change event on your select element.

document.getElementById("yourSelect").addEventListener("change", setNewRegion);

Then, set your localStorage (I supposed that your options value is the country code)

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

I recommend to make a function that test if localStorage is supported once and store the result in a global variable.

Hope this help

First, you have to establish if the cookies has already been set, and if they are: redirect. If not: set the cookie if a form is submitted

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

The conversion for expire times:

time() + (60*n)   =>   n minutes
time() + (60*60*n)   =>   n hours
time() + (60*60*24*n)   =>   n days
time() + (60*60*24*365*n)   =>   n years