简体   繁体   中英

How do I use sessions across subdomains on localhost?

I am storing all sessions in MySQL via session_set_save_handler , but now I'd need to use sessions across subdomains on localhost. Does that even work on localhost?

I already added:

ini_set('session.cookie_domain', '.localhost');

to my code, but that didn't seem to solve the problem either, probably because I am running the code on localhost. Or is there any workaround to be able to use it on localhost?

BTW, I am using XAMPP on Win7.

Example:

http://localhost has the session_id 2oog13m67rr1sd1gk94lbf1he2

and

http://sub.localhost has the session_id 3vr0pdqljothmmf4btlenvk047

So, I guess you just can't use .localhost for the session.cookie_domain .

I tried setting cookies for .localhost.com and it worked. You can add in your machine's hosts file an entry for localhost.com to point to 127.0.0.1 and then browser will forward cookies of localhost.com to http://sub.localhost.com .

It worked for me on node.js, I think similar thing should work on php as well

Since you are already making up domain names, I suggest you don't reuse the top level domain. Either use one you own or invent a brand new one. The name localhost already has a well-defined meaning and that can lead to issues like the one you are facing. Particularly, browsers impose restrictions based on TLD's so you are not able to, eg, set a cookie .com or .co.uk . I'm pretty sure that localhost has its own rules as well in most browsers.

Update: If you are using Chrome, see this bug report resolved as invalid :

You can only set domain cookies for registry controlled domains, ie something ending in .com or so, but not IPs or intranet hostnames like localhost

Related question: Localhost Cookie

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