温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Cookie的理解

发布时间:2020-08-03 20:58:55 来源:网络 阅读:320 作者:ThreadNew 栏目:web开发

1》cookie详解


什么是cookie

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.

     cookie(“小甜饼”)就是服务器发送到我们web浏览器的一小块数据。浏览器会存储它并且当下次再访问同一个网站,web服务器会先看看它上次有没有他上次留下的cookies资料,有的话会依据cookie里的内容来判断使用者,送出特定的网页内容给你。


cookie的三大作用

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

-Personalization(个性化设置)
     User preferences,themes,and other settings

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

    当服务器接收到一个http请求时会发送一个Set-Cookie的响应头,这cookie通常会被浏览器存储,并且这cookie会被写在访问同一个服务器的http请求头中。此外,我们使用了cookie的一些属性来限定cookie的使用。例如Domain属性能够在浏览器端对cookie发送进行限定;Expires属性则指定了该Cookie保存的时间限制;属性Path,则用来指定Cookie将被发送到服务器的哪一个目录路径下。

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

永久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和Path指令定义cookie的范围:cookie应发送到哪些URL。
Domain指定允许的主机接收cookie。如果未指定,则默认为当前文档位置的主机,不包括子域。如果指定了域,则始终包含子域。
例如,如果设置了Domain = mozilla.org,则cookie将包含在developer.mozilla.org等子域中。
Path表示在请求的URL中必须存在的URL路径,以便发送Cookie标头。 %x2F(“/”)字符被视为目录分隔符,子目录也将匹配。
For example, if Path=/docs is set, these paths will match:

/docs
/docs/Web/
/docs/Web/HTTP     

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI