10

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.

Gumbo
  • 594,236
  • 102
  • 740
  • 814
nilacqua
  • 153
  • 1
  • 1
  • 7

2 Answers2

15

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.

Powerlord
  • 82,184
  • 16
  • 119
  • 164
  • Hi @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 – louis.luo Sep 13 '12 at 19:30
  • @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. – Powerlord Sep 13 '12 at 19:50
  • Thanks @Powerlord . I am dealing with some problem like this, but your answer at least confirmed that this should be possible. Thanks! – louis.luo Sep 13 '12 at 20:51
  • So if you own a.example and b.example.com but nothing else .example.com then this isn't a viable solution... – Michael Mar 29 '18 at 04:24
4

If you set the cookie domain to ".example.com", the cookie will work for all subdomains.

Amy B
  • 17,377
  • 12
  • 61
  • 81
  • I wondering if I could be specific to which domains the cookie is sent to. – nilacqua Mar 17 '10 at 19:24
  • @nilacqua: No. If the cookie is set for .example.com, it will be visible for any subdomain of example.com – Piskvor left the building Mar 17 '10 at 19:26
  • Would 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? – Matt Aug 25 '20 at 18:44