Setting cookies for multiple sub-domains
13,618
Solution 1
Webpages can only set cookies for the second (or higher) level domain that they belong to.
This means that secure.example.com
can read and set cookies for secure.example.com
or .example.com
, the latter of which can also be read and set by www.example.com
One last note: If the secure flag is set on a cookie, it can only be read and set over an https connection.
Solution 2
If you set the cookie domain to ".example.com", the cookie will work for all subdomains.
Author by
nilacqua
Updated on June 04, 2022Comments
-
nilacqua almost 2 years
Is it possible to set a cookie for http://www.example.com from a PHP file located at https://secure.example.com? I have some code that was given to me, that appears to try and fails at this. I was wondering if this is possible at all.
-
nilacqua about 14 yearsI wondering if I could be specific to which domains the cookie is sent to.
-
Piskvor left the building about 14 years@nilacqua: No. If the cookie is set for .example.com, it will be visible for any subdomain of example.com
-
louis.luo over 11 yearsHi @Powerlord, does that mean I can use the Javascript on secure.example.com to set a cookie for .example.com too? By just changing the value for
document.cookie
? Thx -
Powerlord over 11 years@Louis_PIG I don't have a lot of experience dealing with cookies in JavaScript. I would think you'd be able to do that, though... as I recall, it's part of the Cookie standard.
-
louis.luo over 11 yearsThanks @Powerlord . I am dealing with some problem like this, but your answer at least confirmed that this should be possible. Thanks!
-
Michael about 6 yearsSo if you own a.example and b.example.com but nothing else .example.com then this isn't a viable solution...
-
Matt over 3 yearsWould this work for all subsub domains as well. Like would .example.com work on sub.example.com and sub.sub.example.com? Or would you have to do .sub.example.com to make that work?
-
zomars over 2 yearsThis won't work on www-less domains tho
https://example.com