简体   繁体   中英

Cookies in JS and PHP

I have 2 virtual hosts and I want to set Cookie on the one of them with JS:

var CSRF = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
$(".form-token").text(CSRF);
document.cookie = "CSRFToken=" + CSRF;

And then I want to try fetch this on the other host with PHP. But var_dump($_COOKIE); outputs just _ga variable. What am I doing wrong?

You cannot share cookies between two hosts that are at the same level of the tld (eg two subdomains), you can only share cookies from a higher level.

Eg, a cookie set on first.exemple.com cannot be read on second.exemple.com .

But if you do it from the higher level it can work: a cookie set on .exemple.com (while being on exemple.com ) can be read on both first.exemple.com and second.exemple.com .

  1. It has to be set while on higher domain (the user must be on a page of exemple.com , not on one of the subdomains), and
  2. the cookie domain must include the leading dot (a cookie set on exemple.com cannot be read by subdomains, but one set on .exemple.com can)

Make good note that www.exemple.com is not the same as exemple.com

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