4

I am trying to set a cookie from "example.com" so that it's only accessible to 'site.example.com'. The problem is that this does not work for some reason. For example, the code below works correctly:

setcookie('my_var', "hello", time()+3600, "/", 'example.com');

That is, when ran from example.com, then I can see the 'my_var' cookie from the site.example.com. However, the code below does not set the cookie:

setcookie('my_var', "hello", time()+3600, "/", 'site.example.com');

(neither does if I prepend a dot, like '.site.example.com')

Using php 5.3.8 and chromium

periklis
  • 9,667
  • 6
  • 55
  • 63
  • You'll might find if you inspect the headers on your request that the cookie header is being sent, but your browser is ignoring it – Paul Dixon Jan 31 '12 at 15:23
  • 2
    You can’t set a cookie for a sub domain, only for the same or a super domain. – Gumbo Jan 31 '12 at 15:24
  • 1
    @gumbo: you mean that I can set a cookie from site.example.com to be accessible for example.com, but not the other way? – periklis Jan 31 '12 at 15:26
  • 2
    @periklis Yes, exactly. See also http://stackoverflow.com/a/5258477/53114. – Gumbo Jan 31 '12 at 15:35
  • possible duplicate of [Domain set cookie for subdomain](http://stackoverflow.com/questions/5258126/domain-set-cookie-for-subdomain) – Gumbo Jan 31 '12 at 15:38
  • I see, thanks. Do you know if there's a RFC or something where this is described? why don't you post this as an answer so I can set it as replied – periklis Jan 31 '12 at 15:38
  • 1
    @periklis I’ve already posted a link to the corresponding RFC and updated the post only just to comply with the recent RFC update. – Gumbo Jan 31 '12 at 15:55

2 Answers2

2

As Gumbo noted in his comment, you can’t set a cookie for a sub domain, only for the same or a super domain, see Domain set cookie for subdomain

Community
  • 1
  • 1
periklis
  • 9,667
  • 6
  • 55
  • 63
1

In my case, I was trying to set a cookie from sd1.example.com to work on example.com, www.example.com, sd2.example.com etc.

I tried changing some settings in php.ini, explicitly listing all subdomains, but none worked. I realized that only the root domain can set cookies on other subdomains and one subdomain cannot set a cookie on another.

So I made a script setcookie.php on the root domain, i.e. example.com

sd1.example.com sends a GET request to this script:

header("Location: //example.com/setcookie.php?value=" . $xxxxx);

And in setcookie.php

setcookie("xxxxx", $_GET['value'], 0, "/", ".example.com");

This way the cookie can be accessed from all subdomains by default.

Tanmay Vij
  • 191
  • 2
  • 13