Set a cookie from the main domain for a subdomain

I have a web site consisting of three domains: domain.com

, sub1.domain.com

and sub2.domain.com

.

Now I want to get via AJAX on the sub1.domain.com page on the .com domain that sets the cookie. This cookie must be available for all three domains.

I tried: setcookie('name','value',time()+3600,'/','.domain.com');

and I tried: setcookie('name','value',time()+3600,'/','domain.com');

(look at the dot in front of the domain, I was told that older browsers would not agree with it). But it didn't work. In fact, there is no set of cookies.

How do I set up a cookie for an AJAX request from a subdomain? I have already added header('Access-Control-Allow-Origin: *');

setcookie to the page.

+3


source to share


1 answer


Several things are required when using credentials:

  • withCredentials

    flag

AJAX must be set in the request xhr.withCredentials = true;

.

  • Access-Control-Allow-Credentials

The server should also respond header('Access-Control-Allow-Credentials: true');

.

  • Invalid wildcard value


When specified, the withCredentials

server cannot specify a start *

. Therefore, you must answer 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 can do something like the following:

if (substr($_SERVER['HTTP_ORIGIN'], -11) === '.domain.com') {
    header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}

      

This sets a valid start to the request header value Origin

, but only if it's in your domain.

+4


source







All Articles