PHP setcookie() for domain but NOT subdomains

后端 未结 4 885
盖世英雄少女心
盖世英雄少女心 2020-12-30 08:46

Is there any way to set a cookie that is not readable on subdomains? In other words, have the cookie available on domain.com, but not

相关标签:
4条回答
  • 2020-12-30 08:56

    Of cource you can! That's what most websites do. Even the built-in php function session_start() does that. and its Set-Cookie http response header looks just as simple as this:

    Set-Cookie: PHPSESSID=fe26eaac143ef75ffcbc91bbe5780d0d; path=/
    

    According to RFC 6265, section 4.1.2.3, the last statement in the paragraph:

    If the server omits the Domain attribute, the user agent will return the cookie only to the origin server.

    So, all you have to do is to omit the domain attribute while setting the cookie from your domain.com

    setcookie($name,$value,$expires,'/','');
    

    For further confirmation, I tested it myself, and I can assure you, cookies aren't accessible from subdomains when you set 'em while omitting the domain attribute.

    0 讨论(0)
  • 2020-12-30 09:00

    this is the reason why quite a few sites (including this one) register a dedicated domain for use as a CDN.

    0 讨论(0)
  • 2020-12-30 09:01

    It is not possible as the cookie domain is tail matched against the domain name. You will have to go with www.

    0 讨论(0)
  • 2020-12-30 09:07

    Apparently, having a cookie on "domain.com" that will match "*.domain.com" is expected behaviour.

    For instance : PERSISTENT CLIENT STATE HTTP COOKIES state (some emphasis mine) :

    domain=DOMAIN_NAME

    When searching the cookie list for valid cookies, a comparison of the domain attributes of the cookie is made with the Internet domain name of the host from which the URL will be fetched. ...
    "Tail matching" means that domain attribute is matched against the tail of the fully qualified domain name of the host. A domain attribute of "acme.com" would match host names "anvil.acme.com" as well as "shipping.crate.acme.com".

    Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT".

    So, you'll either have to :

    • use "www.domain.com" for your site
    • or use a totally different domain name for your static content (like ".anotherdomain.com")
      • for instance, this is what is done on stackoverflow : static content is served from sstatic.net
    0 讨论(0)
提交回复
热议问题