I'm not exactly sure what the problem is but the cookies aren't available for subdomains. Is there any way around this, or is there a better way to set the cookies domain? Thanks!

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, '/'); 

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

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

Recommended Answers

All 5 Replies

I see two problems here:

  1. the function session_start() is missing and so the session cookie will not be created;
  2. the set_cookie() for city is lacking of the domain attribute, so, if you want to make it available only for the current subdomain, it should be:

    set_cookie('city', 'value', 'ttl', 'path', 'sub.domain.com');

I just want to make sure so can you provide the whole script? Thanks!

I intended this:

ini_set("session.cookie_domain", ".example.com"); 

If you use Chrome//Firefox console, you can check the cookies created for the current domain. You cannot create a cookie for another domain or subdomain, but the dot gives you the ability to extend the cookie to subdomains. If, for example, you are on miami.example.com domain, you can:

setcookie('city', 'miami', time()+300, '/', '.miami.example.com');

That way, when you access to: hotels.miami.example.com or airports.miami.example.com the city cookie will be available.

Also, please, do not open multiple threads with the same question, I just noticed, there is already another one:

Thanks cereal. I think this is the right direction to extend the cookie to subdomains '.miami.example.com', but not whole script is executed.

Member Avatar

Also, please, do not open multiple threads with the same question, I just noticed, there is already another one

This user did the same with a previous question. Please take note that this not only creates confusion, but is a slap in the face to contributors who are in the process of helping in the original thread. It's as if their input is not appreciated. Please desist.

Be a part of the DaniWeb community

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