Cookie 与 Web 存储 [重复]

Posted

技术标签:

【中文标题】Cookie 与 Web 存储 [重复]【英文标题】:Cookies vs. Web storage [duplicate] 【发布时间】:2016-04-11 11:57:18 【问题描述】:

我正在创建一个项目,我想在其中保存用户达到的最后一个级别,以便他们可以在下次离开的地方继续。我想知道是否应该使用 cookie 或网络存储,以及使用每一个的原因。例如,一种是否会影响性能,一种是通常启用/禁用的,一种是现代浏览器不支持的,等等。

我也想知道除了这两个之外是否还有其他选项可以替代,以及它们的优点和缺点是什么。

谢谢!

【问题讨论】:

【参考方案1】:

**Cookies**
Pros
1. Legacy support (it's been around forever)
2. Persistent data
3. Expiration dates

Cons
1. Each domain stores all its cookies in a single string, which can make parsing data difficult
2. Data is unencrypted.
3. small in size, cookies are sent with every HTTP request
4. Limited size (4KB)
5. SQL injection can be performed from a cookie

**Local storage / Web storage**
Pros
1. Support by most modern browsers
2. Persistent data that is...
3. stored directly in the browser
4. Same-origin rules apply to local storage data
5. Is not sent with every HTTP request
6. ~5MB storage per domain (that's 5120KB)

Cons
Not supported by anything before:
1. IE 8
2. Firefox 3.5
3. Safari 4
4. Chrome 4
5. Opera 10.5
6. ios 2.0
7. android 2.0
8. If the server needs stored client information you purposefully have to send it. [3]



Based on my comparison I think that local storage is the logical successor of cookies for storing client-side data. While cookies were originally created as a work-around, local storage has been designed with a purpose.

Local storage is easier to work with because you don't have to parse a string to get data. Instead you can make a call for the variable name and it's value is returned. The same applies with creating and deleting data as well.

For saving client-side data I believe local storage wins. As someone on the *** boards pointed out however, if your server needs information from a client cookies will be a better solution. But if you just want to save user-prefs, num vists, or other stuff like that choose local storage.

【讨论】:

【参考方案2】:

它们的目的完全不同。 Cookie 可从服务器获得,而 Web 存储仅可用于客户端。每个请求,cookies 将与 HTTP 标头一起发送到服务器。当服务器不需要数据时,这不是必需的。在这种情况下,Web Storage 可能是要走的路。

这完全取决于您希望谁访问数据。

网络存储提供了一种永久存储数据的方法(直到用户清除其浏览器缓存),而 cookie 设置为在特定时间后过期。

Web Storage 也更适合存储大块数据,例如数据的完整 JSON 表示形式(最大 5MB)。 IE8及以上支持Web Storage,应该没问题。

【讨论】:

以上是关于Cookie 与 Web 存储 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

使用 Jquery 设置 cookie [重复]

JQuery保存和读取$ .cookie存储对象[重复]

cookie和session页面随机数和防止重复提交

PHP记住cookie中的登录状态[重复]

PHP登录系统:记住我(持久cookie)[重复]

FileSystemWatcher 在功能后不会触发 [重复]