Should cookie values be URL encoded?

前端 未结 3 915
你的背包
你的背包 2020-12-10 03:25

When setting cookies, PHP url-encodes the cookie value (at least when not using setrawcookie) and it url-decodes the cookie value before making

相关标签:
3条回答
  • 2020-12-10 03:31

    Stolen from NCZOnline:

    There is some confusion over encoding of a cookie value. The commonly held belief is that cookie values must be URL-encoded, but this is a fallacy even though it is the de facto implementation. The original specification indicates that only three types of characters must be encoded: semicolon, comma, and white space. The specification indicates that URL encoding may be used but stops short of requiring it. The RFC makes no mention of encoding whatsoever. Still, almost all implementations perform some sort of URL encoding on cookie values. In the case of name=value formats, the name and value are typically encoded separately while the equals sign is left as is.

    0 讨论(0)
  • 2020-12-10 03:34

    Yes. While it's not required per the spec, the following is mentioned in RFC6265 (emphasis is in the original document, not added)

    To maximize compatibility with user agents, servers that wish to store arbitrary data in a cookie-value SHOULD encode that data, for example, using Base64 [RFC4648].

    In my experience, most web frameworks and libraries for cookies have methods for encoding/decoding cookie values. In many cases, esp. in frameworks and high-level languages, this is abstracted away and done automatically.

    This answer provides a fairly detailed of the history behind the values allowed in cookies. Might be of interest to you.

    0 讨论(0)
  • 2020-12-10 03:52

    sytech's answer (which I have accepted) is certainly correct as it quotes the spec, but since the spec is rather vague, here's an overview how some web frameworks actually handle the matter:

    RFC6265:           "for example Base64"
    PHP:               URL encode
    Go:                raw
    Node.js + Express: URL encode
    
    0 讨论(0)
提交回复
热议问题