Search code examples
phpcookieshttp-redirectuser-inputversions

Use javascript to redirect to UK or Irish version of the site


I am working on a site where there are UK and Irish sub-folders. Both sites work off the one CMS, inside which there is an Irish section and UK section. I want to store a cookie that contains the version of the site they choose from the drop down

My code so far is Index.html

<form id="region_select" name="region_select" action="/includes/region-val.php" method="post">
        <select id="region-picker" name="region-picker" onchange="this.form.submit();">
            <option>--- Please Select Your Region ---</option>
            <option value="IE" id="IE" name="set_region[IE]">Visit Irish Website</option>
            <option value="UK" id="UK" name="set_region[UK]">Visit UK Website</option>
        </select>
        <input type="submit" name="submit_region" value="Go!"/>
        </form>

My region-val.php code is

 if (isset($_POST["submit_region"])) {
        $region = key($_POST["set_region"]);
        setcookie("region", $region, time() + 24 * 3600);
    }  

    if($_COOKIE["region"] == "UK"){
        header('Location:http://google.com');   
    }
    else{
        header('Location:http://yahoo.com');
    }

So far it only redirects to one version of the site.


Solution

  • I don't see why you are giving names to the <options>s inside your <select>. It's the select's name that is important.

    Change the form to this:

    <form id="region_select" name="region_select" action="/includes/region-val.php" method="post">
      <select id="region-picker" name="region-picker" onchange="this.form.submit();">
        <option>--- Please Select Your Region ---</option>
        <option value="IE">Visit Irish Website</option>
        <option value="UK">Visit UK Website</option>
      </select>
      <input type="submit" name="submit_region" value="Go!"/>
    </form>
    

    The name you gave to the <select> is region-picker - so it's the value of that input you are interested in. The PHP should look like this:

    if (isset($_POST["region_picker"])) {
        $region = $_POST["region_picker"]);
        // Maybe you should check here that the user has submitted a valid region
        setcookie("region", $region, time() + 24 * 3600);
    }  
    
    if($_COOKIE["region"] == "UK"){
        header('Location:http://google.com');   
    }
    else{
        header('Location:http://yahoo.com');
    }