0

I have two cookies with the same name set - one on my root domain, and one on a subdomain. By default, if you are on a matching subdomain, PHP will read the subdomain cookie and ignore the root cookie. How would I read the root domain cookie when there is a matching subdomain cookie?

For example, lets say I have these two cookies:

Name | Value | Domain
uid  | 12345 | .example.com
uid  | abcde | app.example.com

If I am on app.example.com, PHP will only show me this in the $_COOKIE global array:

array("uid" => "abcde");

However, I want to be able to access this:

array("uid" => "12345");

Is this possible?

I've tried using session_set_cookie_params like this:

session_set_cookie_params(0, "/", ".example.com");
session_start();
echo "<pre>"; print_r($_COOKIE["uid"]); echo "</pre>";

But it still returns:

array("uid" => "abcde");

EDIT:

The cookies are being set with the following code:

setcookie("uid", "12345", 0, "/", "example.com");
setcookie("uid", "abcde", 0, "/", "app.example.com");
Matt Koskela
  • 5,269
  • 3
  • 26
  • 29
  • For sessions, http://stackoverflow.com/questions/644920/allow-php-sessions-to-carry-over-to-subdomains for other cookies, you need to just specify the domain like you are doing but using setcookie. – Jonathan Kuhn Feb 28 '14 at 00:05
  • as far as I know, the browser only sends one of those cookies, so PHP doesn't even know about the other one. Basically the browser checks that there are no cookies with the same name. If there are, it will send the one with the most specific domain value appropriate for that domain (so on app.example.com it `"app.example.com"` is more specific than `".example.com"` which in turn would be more specific than `"example.com"`) – Tularis Feb 28 '14 at 00:05
  • @JonathanKuhn - specifying the domain isn't doing anything... It will always just show the cookie from the subdomain if you are on that subdomain. – Matt Koskela Feb 28 '14 at 19:18
  • Is the cookie being set on the main domain using the same method? You can't access the cookie from the subdomain if it was not set properly. Also, you are using session_set_cookie_params which will only affect the session cookie, but area looking at `$_COOKIE['uid']` which, unless it has been renamed, is not the session cookie. – Jonathan Kuhn Feb 28 '14 at 19:22
  • I just added some code how I'm setting each cookie. You're right about the session stuff - I'm not using the session cookie, which makes that function irrelevant. – Matt Koskela Feb 28 '14 at 20:12

1 Answers1

1

if you create a cookie in the root domain accessible for other subdomains and you do not use this cookie for this subdomain, I recommend you to rename the subdomain's cookie.

Aaronidas
  • 138
  • 2
  • 7