steveneaston
steveneaston

Reputation: 259

Cookie not recognised on subdomain

I have a domain and a subdomain which I need both to recognise a cookie set by the main domain. On www.mydomain.com I set the cookie with Javascript like so:

var d = new Date();
d.setDate(d.getDate() + 30);
var c = "all; expires=" + d.toUTCString() + "; path=/;domain=mydomain.com";
document.cookie = "cookies=" + c;

In the PHP I use a simple if (isset($_COOKIE['cookies'])) ... This works on www.mydomain.com but it doesn't work on sub.mydomain.com.

Any suggestions? Do I have to call the cookie within PHP differently?

Upvotes: 0

Views: 123

Answers (2)

Colin M
Colin M

Reputation: 13328

Change domain=mydomain.com to domain=.mydomain.com (notice the preceding dot). Then the cookie will apply to all subdomains.

Upvotes: 2

fnkr
fnkr

Reputation: 10065

var d = new Date();
d.setDate(d.getDate() + 30);
var c = "all; expires=" + d.toUTCString() + "; path=/;domain=.mydomain.com";
document.cookie = "cookies=" + c;

Upvotes: 1

Related Questions