Cookies on localhost with explicit domain

前端 未结 21 2119
[愿得一人]
[愿得一人] 2020-11-22 04:17

I must be missing some basic thing about cookies. On localhost, when I set a cookie on server side and specify the domain explicitly as localhost (or .localhost). t

21条回答
  •  时光取名叫无心
    2020-11-22 05:09

    I broadly agree with @Ralph Buchfelder, but here's some amplification of this, by experiment when trying to replicate a system with several subdomains (such as example.com, fr.example.com, de.example.com) on my local machine (OS X / Apache / Chrome|Firefox).

    I've edited /etc/hosts to point some imaginary subdomains at 127.0.0.1:

    127.0.0.1 localexample.com
    127.0.0.1 fr.localexample.com
    127.0.0.1 de.localexample.com
    

    If I am working on fr.localexample.com and I leave the domain parameter out, the cookie is stored correctly for fr.localexample.com, but is not visible in the other subdomains.

    If I use a domain of ".localexample.com", the cookie is stored correctly for fr.localexample.com, and is visible in other subdomains.

    If I use a domain of "localexample.com", or when I was trying a domain of just "localexample" or "localhost", the cookie was not getting stored.

    If I use a domain of "fr.localexample.com" or ".fr.localexample.com", the cookie is stored correctly for fr.localexample.com and is (correctly) invisible in other subdomains.

    So the requirement that you need at least two dots in the domain appears to be correct, even though I can't see why it should be.

    If anyone wants to try this out, here's some useful code:

    
    
    
    Testing cookies
    
    
    
    ";
        setcookie("mycookie", $val, time() + 48 * 3600, '/', $domain);
    }
    print "
    ";
    print "Cookie:
    "; var_dump($_COOKIE); print "Server:
    "; var_dump($_SERVER); print "
    "; ?>

提交回复
热议问题