I started using PHP a couple of months ago. For the sake of creating a login system for my website, I read about cookies and sessions and their differences (cookies are stored in the user's browser and sessions on the server). At that time, I preferred cookies (and who does not like cookies?!) and just said: "who cares? I don't have any good deal with storing it in my server", so, I went ahead and used cookies for my bachelor graduation project. However, after doin' the big part of my app, I heard that for the particular case of storing user's ID, sessions are more appropriate. So I started thinking about what would I say if the jury asks me why have you used cookies instead of sessions? I have just that reason (that I do not need to store internally information about the user). Is that enough as a reason? or it's more than that? Could you please tell me about advantages/disadvantages of using cookies for keeping User's ID?

感谢大家在StackOverflow!


当前回答

会话允许您像使用cookie一样存储单独的信息片段,但是数据存储在服务器上而不是客户机上。

其他回答

这个概念是跨页面加载为web访问者存储持久数据。cookie直接将其存储在客户机上。会话使用cookie作为某种密钥,与存储在服务器端的数据相关联。

最好使用会话,因为实际值对客户端隐藏,您可以控制数据何时过期并失效。如果它完全基于cookie,用户(或黑客)可以操纵他们的cookie数据,然后向您的站点发送请求。

编辑:我不认为使用cookie有任何好处,除了简单。这样看……用户有任何理由知道他们的ID号吗?通常我会说不需要,用户不需要这些信息。在需要知道的基础上,提供信息应该受到限制。如果用户将cookie更改为不同的ID,应用程序将如何响应?这是一个安全隐患。

在会话盛行之前,我基本上有自己的实现。我在客户机上存储了一个唯一的cookie值,并将我的持久数据与该cookie值一起存储在数据库中。然后在页面请求中,我匹配这些值并获得持久数据,而不让客户端控制这些数据。

实际上,session和cookie并不总是分开的。会话通常(但不总是)使用cookie。

你的问题在这里的其他问题中有一些很好的答案。因为你的问题是专门关于保存用户的IDU(或ID)的,我不认为它与其他问题完全相同,但他们的答案应该对你有帮助。

cookie vs会话

缓存VS会话VS cookie ?

会话和Cookie的区别是什么?

区分这两者的基本思路。

会话:

UID存储在服务器端(即服务器端) 更安全(因为1) 过期不能设置,会话变量将在用户关闭浏览器时过期。(现在php默认存储24分钟)

饼干:

UID存储在web浏览器上(即客户端) 不是很安全,因为黑客可以到达并获得你的信息(因为1) 可以设置过期时间(有关详细信息,请参阅setcookies())

当您需要存储短期信息/值时,例如用于计算、测量、查询等的变量时,会话是首选。

当您需要存储长期的信息/值时,例如用户的帐户(这样即使他们关闭计算机2天,他们的帐户仍然会登录),首选cookie。我想不出很多关于cookie的例子,因为它在大多数情况下都没有被采用。

I will select Session, first of all session is more secure then cookies, cookies is client site data and session is server site data. Cookies is used to identify a user, because it is small pieces of code that is embedded my server with user computer browser. On the other hand Session help you to secure you identity because web server don’t know who you are because HTTP address changes the state 192.168.0.1 to 765487cf34ert8ded…..or something else numbers with the help of GET and POST methods. Session stores data of user in unique ID session that even user ID can’t match with each other. Session stores single user information in all pages of one application. Cookies expire is set with the help of setcookies() whereas session expire is not set it is expire when user turn off browsers.

正如其他人所说,Sessions很聪明,而且在向客户端隐藏信息方面更有优势。

但是Cookie至少还有一个优势,你可以从Javascript访问你的Cookie(例如ngCookies)。使用PHP会话,您不能在PHP脚本之外的任何地方访问它。