An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. The browser may store it and send it back with the next request to the same server. Typically, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.



-Session management
     logins,shopping carts,game scores,or anything else the server should remember

     User preferences,themes,and other settings

     Recording and analyzing user behavior

Create Cookies (创建cookie)

When receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header. An expiration date or duration can be specified, after which the cookie is no longer sent. Additionally, restrictions to a specific domain and path can be set, limiting where the cookie is sent.


The Set-Cookie and Cookie headers

Set-Cookie 的响应头会从服务器端发送cookie到浏览器端。

HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry

[page content]

现在每个新的请求,浏览器会利用cookie 头把所有先前存储的cookies发送到服务器。

GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry

Session cookie

上面的cookie是一个session cookie:当客户端关闭时它会被删除。因为它没有指定Expires或Max-Age指令。但是,Web浏览器可能会使用会话还原,这会使大多数会话cookie永久保留,就像浏览器从未关闭一样。

Permanent cookie


Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;

Secure and HttpOnly cookies

安全cookie仅通过HTTPS协议通过加密请求发送到服务器。但是尽管安全,重要的东西还是不能放在cookie中。为了防止跨站点脚本(XSS)***,JavaScript的Document.cookie API无法访问HttpOnly cookie;它们只被发送到服务器。

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

Scope of cookies(cookies 范围)

例如,如果设置了Domain = mozilla.org,则cookie将包含在developer.mozilla.org等子域中。
Path表示在请求的URL中必须存在的URL路径,以便发送Cookie标头。 %x2F(“/”)字符被视为目录分隔符,子目录也将匹配。
For example, if Path=/docs is set, these paths will match: