如何创建持久性和非持久性cookie? [英] How do I create a persistent vs a non-persistent cookie?

查看:298
本文介绍了如何创建持久性和非持久性cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎不知道如何创建持久性vs非持久性cookie。

解决方案

Cookie具有隐式或显式设置的到期日期它控制他们持续多长时间(受用户代理实际执行它的影响)。 Cookie可能仅在会话持续时间(或更短的时间)内持续存在。



如果Cookie有效,则会与HTTP请求一起传递它源自的域。只有设置cookie的域可以读取cookie(虽然有方法可以利用这一点,如跨站点脚本)。




  • 如果您希望Cookie在特定时间过期,请使用您选择的客户端或服务器端语言在其上设置到期日期。$ / b>


  • 如果您希望Cookie在会话结束时过期,请不要设置
    的过期日期。




从RFC(强调我):


Cookie设置器可以指定
删除日期,在这种情况下,
cookie将在该日期删除。



如果Cookie设置器未指定
a日期,则一旦
用户退出其浏览器,就会移除该Cookie。



因此,指定日期是
使cookie在
会话中生存的一种方式。 因此,具有到期日期的Cookie
称为
persistent。



作为示例应用程序,
a购物网站可以使用持久性
cookie存储用户有
放置在他们的篮子里的项目。 (实际上,
该cookie可以指存储在购物网站的
数据库中的条目,
不在您的计算机上。)这样,如果
用户退出他们的浏览器没有
进行购买并稍后返回,
他们仍然在
篮子中找到相同的项目,因此他们不必再次查找
这些项目。如果这些cookie
没有过期日期
,当浏览器
关闭时,它们将过期,并且关于
篮子内容的信息将丢失。



I can't seem to figure out how to create a persistent vs a non-persistent cookie. How do they differ, say, in the HTTP headers that are sent back?

解决方案

Cookies have an expiration date implicitly or explicitly set which controls how long they last (subject to the user agent actually enforcing it). A cookie may persist only for the duration of the session (or an even shorter period).

If a cookie is valid, it will be passed along with the HTTP request to the domain that it originated from. Only the domain that set the cookie can read the cookie (though there are ways to exploit this, such as cross-site scripting).

  • If you want a cookie to expire at a specific time, set an expiration date on it using the client or server-side language of your choice.

  • If you want the cookie to expire when the session ends, don't set an expiration date.

From the RFC (emphasis mine):

The cookie setter can specify a deletion date, in which case the cookie will be removed on that date.

If the cookie setter does not specify a date, the cookie is removed once the user quits his or her browser.

As a result, specifying a date is a way for making a cookie survive across sessions. For this reason, cookies with an expiration date are called persistent.

As an example application, a shopping site can use persistent cookies to store the items users have placed in their basket. (In reality, the cookie may refer to an entry in a database stored at the shopping site, not on your computer.) This way, if users quit their browser without making a purchase and return later, they still find the same items in the basket so they do not have to look for these items again. If these cookies were not given an expiration date, they would expire when the browser is closed, and the information about the basket content would be lost.

这篇关于如何创建持久性和非持久性cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆