I have the cookies and subdomain selection for header:

<script type="text/javascript" src="/static/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(function(){
var city = readCookie('city');
if(city !=null && city !=''){
window.location.href = 'http://' + city + '.example.com';
}
$('#citygo').change(function(){
var city = $(this).val();
window.location.href = 'http://' + city + '.example.com';
});
});

function createCookie(name,value,days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script>


<select id="citygo">
<option value="0">Select City</option>
<option value="amsterdam">Amsterdam</option>
<option value="newyork">New York</option>
<option value="london">London</option>
<option value="cardiff">Cardiff</option>
</select>

Now I need to work on the server side to set cookies to remember and redirect to a visited subdomain. The code below is not working but should be something like that. Would someone show me how to set cookie? Any help will be very much appreciated.

<?php 
if (isset($_COOKIE["city"])) { 
if ($_COOKIE["city"] == 'city') { 
header("window.location.href = 'http://' + city + '.example.com'"); 
} 
} 
?>

Thanks Lsmjudoka. Can I just use javascript and forget about php code?

echo "<script type='text/javascript'>window.location.href = 'http://" . $city . ".example.com";

You can - though that example is dependent on $city being the value from the cookie. Are you talking about using PHP to set/read the cookie, but then doing the redirect with JavaScript?

I prefer to work on the server side using PHP to set/read the cookie. I got a better script now but the cookie is still not working and the domain cannot redirect to sub-domain when I type on the web browser. The reason could be the same script that I put on both main domain and sub-domain. Any idea? thanks.

<?php 
ini_set("session.cookie_domain", ".example.com"); 

if( isset($_POST['city']) && $_POST['city'] != '' ){ 
    $cookie_expire = time() + 50400;  
    setcookie('city', $_POST['city'], $cookie_expire, '/'); 

    header("Location: http://".$_POST["city"].".example.com"); 
    die(); 
} 

if (isset($_COOKIE["city"])) { 
    $subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST'])); 

    if ($_COOKIE["city"] != $subdomain) { 
        header("Location: http://".$_COOKIE["city"].".example.com"); 
        die(); 
    } 
}

As a note, session.cookie_domain only applies to the session cookie used by PHP for session_start() and the $_SESSION array. To set the domain for your cookies you'll have to do that in the setcookie function, it's the 5th paramater (right after path).

With that said I don't think that's your problem. I'm not immediately seeing anything wrong, can you explain more about when it does/doesn't work or post more of the code, for instance the HTML form for submitting the city variable?

I am not exactly sure what the problem is but the cookies aren't available for subdomains. Cookie set in example.com isn't available to sub.example.com and cookie set in sub.example.com isn't available to example.com. I may not actually need it to work both ways.

Someone used this code for Drupal and should be the solution and way to go. I just have no luck to make it work.

Main Domain:
<?php
function YOUR_MODULE_NAME_init() {
  if(isset($_COOKIE['city'])) {
    header('Location: ' . base64_decode($_COOKIE['city']));
  }
}
?>

Sub-domain
<?php
function YOUR_MODULE_NAME_init() {
  if(!isset($_COOKIE['city'])) {
    setcookie('city', base64_encode($_SERVER['HTTP_HOST']), time()+50400, '/', 'example.com');
    setcookie('city', base64_encode($_SERVER['HTTP_HOST']), time()+50400, '/', 'amsterdam.example.com');
    setcookie('city', base64_encode($_SERVER['HTTP_HOST']), time()+50400, '/', 'newyork.example.com');
    setcookie('city', base64_encode($_SERVER['HTTP_HOST']), time()+50400, '/', 'london.example.com');
  }
  else {
    header('Location: ' . base64_decode($_COOKIE['city']));
  }
}
?>

It should work for all subdomains if you set it to just example.com. In the code you posted they set separate cookies for each subdomain, but that seems excessive.

Try changing your setcookie to this:
setcookie('city', $_POST['city'], $cookie_expire, '/', 'example.com');

Thanks for your suggestion. I have tried already and still not working. Is there a better way to set the cookies domain?

The only way to set it is through the 5th paramater of setcookie(). Just to clarify again, are you actually setting it to "example.com" or are you replacing "example.com" with your website's domain, e.g. "travelabroad.com"?

If that's not the issue I have the feeling it might be something in another part of the script, if you can post the complete script we can see if that's the case.

I use my domain instead of example.com and here is the full script.

//PHP Code
<?php 
ini_set("session.cookie_domain", ".example.com"); 

// Set cookie and redirect when user change city 
if( isset($_POST['city']) && $_POST['city'] != '' ){ 
    $cookie_expire = time() + 50400;  
    setcookie('city', $_POST['city'], $cookie_expire, '/', '.example.com');

    header("Location: http://".$_POST["city"].".example.com"); 
    die(); 
} 

// Redirect if user selected default city 
if (isset($_COOKIE["city"])) { 
    $subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST'])); 

    if ($_COOKIE["city"] != $subdomain) { 
        header("Location: http://".$_COOKIE["city"].".example.com"); 
        die(); 
    } 
}
?>


//Javascript
</head>
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

//City selection
$(function(){
    var city = readCookie('city');
    if(city !=null && city !=''){
    window.location.href = 'http://' + city + '.example.com';
    }
$('#citygo').change(function(){
    var city = $(this).val();
    window.location.href = 'http://' + city + '.example.com';
});
});

//Cookies
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+";expires="+date+";domain=.example.com;path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}
</script>
</head>


//City selection
<body>
<select id="citygo">
    <option value="0">Select City</option>
    <option value="amsterdam">Amsterdam</option>
    <option value="newyork">New York</option>
    <option value="london">London</option>
    <option value="cardiff">Cardiff</option>
</select>
</body>

Okay well based on the above code your PHP is never getting a chance to set the cookie. You need to use the <form> tag in your city selection HTML, and the name attribute, like so:

<form action="" method="post">
    <select name="city" id="citygo">
        <option value="0">Select City</option>
        <option value="amsterdam">Amsterdam</option>
        <option value="newyork">New York</option>
        <option value="london">London</option>
        <option value="cardiff">Cardiff</option>
    </select>
    <input type='submit' value='Select' />
</form>

Additionally your JavaScript redirects the site to the subdomain before the cookie can even be set. If you want to maintain that action (as soon as a user changes the city on the select form, the site redirects to that) then you will have to set the cookie using JavaScript.

Do you mean I should have javaScript only and forget about the php code? Can you convert that php code into javaScript?

Assuming your project requires you to have a site with a page for each of several cities (Amsterdam, New York, etc) that contains some city information, I would change your script to something like this (Note that this is a full PHP solution. If for whatever reason you decide to pursue a JavaScript-only solution, I would check out DaniWeb's JS forum for help)

<?php

$cities = array('amsterdam', 'new_york', 'chicago');

if(isset($_COOKIE['city'])) {
    header("Location: " . $_COOKIE['city'] . ".example.com");
    exit;
}
else if(isset($_GET['city'])) {
    if(array_search($_GET['city'], $cities) !== false) {
        setcookie('city', $_GET['city'], time() + (86400 * 7), '/', 'example.com');
        header("Location: " . $_GET['city'] . ".example.com");
        exit;
    }
}
?>



<html>
<body>
<?php
foreach($cities as $city) {
    echo "<a href='http://example.com?city=$city'>" . 
        ucwords(str_replace('_', ' ', $city)) . "</a>";
}
?>
</body>
</html>

The php script doesn't work somehow. Can you please ask the JS forum for help? Thank you so much for your time and help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.