Reputation:
I have a website, consisting of three domains: domain.com
, sub1.domain.com
and sub2.domain.com
.
I now want to get via AJAX on sub1.domain.com a page on domain.com which sets a cookie. This cookie has to be available to all three domains.
I've tried: setcookie('name','value',time()+3600,'/','.domain.com');
and I've tried: setcookie('name','value',time()+3600,'/','domain.com');
(watch the dot before the domain, I was told that old browsers wouldn't accept it.) But this didn't work. In fact, there isn't a cookie set.
How can I set a cookie on an AJAX request from a subdomain? I already added header('Access-Control-Allow-Origin: *');
to the setcookie-page.
Upvotes: 3
Views: 2160
Reputation: 42458
There are a couple of things that are required when using credentials:
withCredentials
flagThe AJAX request needs to have xhr.withCredentials = true;
set.
Access-Control-Allow-Credentials
The server must also respond with header('Access-Control-Allow-Credentials: true');
.
When specifying withCredentials
, the server cannot allow an origin of *
. Therefore, you must respond with a list of valid domains:
header('Access-Control-Allow-Origin: http://sub1.domain.com,http://sub2.domain.com');
If you still want to have an arbitrary list of subdomains, you could do something like the following:
if (substr($_SERVER['HTTP_ORIGIN'], -11) === '.domain.com') {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}
This sets the allowed origin to the value of the Origin
request header, but only if it's on your domain.
Upvotes: 4