简体   繁体   中英

Set a cookie on another domain using ajax and php - FAILS

Domain-Being-Browsed.com has a javascript function, which when triggered makes an ajax call to a php file on another domain: another-domain.com/set-cookie.php

set-cookie.php contains code like this:

header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
$cookie_set = FALSE;
$cookie_set = setcookie( 'cookie_name', 'cookie_value', $a_big_number, '/' );
if( $cookie_set ){  echo 'cookie set!';  }

The javascript function is like this:

var url = 'http://another-domain.com/set-cookie.php';
$.ajax({
  'url': url,
  'xhrFields': {
    withCredentials: true
  }
}).done(function(resp){
console.log(resp);
});

If I visit http://another-domain.com/set-cookie.php in my browser, it sets the cookie. If I trigger the javascript function, I get a response in the console, 'cookie set,', but when I load http://another-domain.com in my browser, I find that the cookie is not there.

I found this post: Can't set cookie on different domain , which seems exactly like mine, but the answer given I've incorporated already and it doesn't help. What am I missing?

As directed by Barmar, I checked the Network tab in dev tools for the Set-Cookie header in the response. It seems that I needed to set 'SameSite' to 'None'. If you set 'Samesite' to none, you have to set 'secure' also. And if you set secure, you have to load the page over https. So the answer, as found in the answer here: How to fix "set SameSite cookie to none" warning? is to change the php file like this:

header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
$cookie_options = array(
    'expires' => time() + 60*60*24*30,
    'path' => '/',
    'secure' => true,
    'samesite' => 'None'
);
$cookie_set = FALSE;
$cookie_set = setcookie( 'cookie_name', 'cookie_value', $cookie_options );
if( $cookie_set ){  echo 'cookie set!';  }

and to load the page over https. Works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM