cookie 值是否应该 URL 编码?

Should cookie values be URL encoded?

设置 cookie 时,PHP url- 对 cookie 值进行编码(至少在不使用 setrawcookie 时) 并 url- 解码在 $_COOKIE.

中的应用程序可用之前的 cookie 值

这是公认的标准吗?如果我将原始 cookie 值设置为 a%3Db,我会在大多数网络编程语言中返回 a=b(通过它们各自的 cookie 读取机制)吗?

是的。虽然根据规范 不需要 ,但 RFC6265 中提到了以下内容(重点在原始文档中,未添加)

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].

根据我的经验,大多数 cookie 网络框架和库都有 encoding/decoding cookie 值的方法。在许多情况下,尤其是。在框架和 high-level 语言中,这是抽象出来并自动完成的。

This answer 对 cookie 中允许的值背后的历史提供了相当详细的说明。您可能会感兴趣。

sytech 的回答(我已经接受)肯定是正确的,因为它引用了规范,但由于规范相当模糊,这里概述了一些网络框架如何实际处理这个问题:

RFC6265:           "for example Base64"
PHP:               URL encode
Go:                raw
Node.js + Express: URL encode

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.