1

I'm trying to set a cookie using PHP on a subdomain (api.example.com) and read it on the main domain (example.com)

My setcookie looks like this: setcookie("user-hash", $userHash, $expiry, "/", $domain, true, true);

Where $domain has been a few different things over the course of the day e.g. "example.com", ".example.com", "" and nothing seems to work.

I'm now wondering if it is something else, or if is even possible? I've seen plenty of people posting examples of how to set/read a cookie on the main domain but not much the other way around.

My cookies worked fine before I moved this script to the subdomain.

Tony Merryfield
  • 383
  • 3
  • 10
  • From a subdomain you can set a cookie for a "parent domain", but not the other way around: https://stackoverflow.com/a/57803192/231316 – Chris Haas Nov 28 '22 at 19:36
  • ```So subdomain.example.com domain-matches example.com, but example.com does NOT domain-match subdomain.example.com``` so does that mean I need to set my domain to `api.example.com`? – Tony Merryfield Nov 28 '22 at 20:39
  • 1
    If you want to set a cookie on api.example.com, the code that sets it must originate from api.example.com, or a subdomain of _that_ such as xyz.api.example.com – Chris Haas Nov 28 '22 at 21:07
  • I want to set a cookie on example.com from api.example.com – Tony Merryfield Nov 28 '22 at 21:19
  • For a basic sign in – Tony Merryfield Nov 28 '22 at 21:21
  • I see, I was interpreting it as the other way. Using a leading period for the domain is an older spec, and I'm fairly certain isn't used by any modern browsers, so just `example.com` would be correct for that. You say it isn't working, but have you inspected the network traffic? On api.example.com do you see that cookie in your browser tools? Same with example.com. Ignore PHP/HTML, too, just visit a page and check your tools to see what is in there. You are also setting secure and HTTP only, are those correct? – Chris Haas Nov 28 '22 at 21:27
  • And, just to make sure, your domain is not on the PSL? https://publicsuffix.org/list/public_suffix_list.dat – Chris Haas Nov 28 '22 at 21:27
  • The secure and httponly flags weren't a problem before my changes - if they need to change though, then I'm not too fussed about them. I'll have to inspect the network on api.example.com but nothing visible on example.com - I'll change the domain to example.com and have a look - thanks. – Tony Merryfield Nov 28 '22 at 21:42

0 Answers0