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!


当前回答

Session和Cookie不是一回事。

会话用于存储来自web页面的信息。通常情况下,网页没有存储这些信息的内存。但是使用我们可以保存必要的信息。

但Cookie是用来识别用户的。使用cookie,我们可以存储数据。它是存储在用户web浏览器中的一小部分数据。当用户下次浏览时,浏览器将cookie数据信息发回服务器,以获取之前的活动。

致谢:Session和Cookie

其他回答

我个人同时使用cookie和session。

Cookies只在用户点击“记住我”复选框时使用。而且cookie是加密的,数据只在服务器上解密。如果有人试图编辑cookie,我们的解密器能够检测到它并拒绝请求。

我看到很多网站的登录信息存储在cookie中,任何人都可以简单地在cookie中更改用户的id和用户名来访问任何人的帐户。

谢谢,

当您将#ID保存为cookie以识别登录用户时,您实际上是在向与他们无关的用户显示数据。此外,如果第三方试图在他们的浏览器中设置随机id作为cookie数据,他们将能够使服务器相信他们是用户,而实际上他们不是。这就是缺乏安全感。

您已经使用了cookie,正如您所说,您已经完成了项目的大部分。此外,cookie具有保留较长时间的特权,而会话结束得更快。所以会话在这种情况下不适合。在现实中,许多著名和流行的网站和服务使用cookie,你可以保持登录很长一段时间。但是如何使用他们的方法来创建更安全的登录过程呢?

here's the idea: you can help the way you use cookies: If you use random keys instead of IDs to recognize logged-in users, first, you don't leak your primary data to random users, and second, If you consider the Random key large enough, It will be harder for anyone to guess a key or create a random one. for example you can save a 40 length key like this in User's browser: "KUYTYRFU7987gJHFJ543JHBJHCF5645UYTUYJH54657jguthfn" and it will be less likely for anyone to create the exact key and pretend to be someone else.

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

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

会话是服务器上与cookie信息相关联的一组信息。如果使用PHP,可以检查会话。保存路径位置,实际上是“查看会话”。 cookie是发送给客户端和从客户端返回的数据片段。cookie通常用于促进会话,因为它告诉服务器哪个客户机处理哪个会话。还有其他方法可以做到这一点(查询字符串魔术等),但cookie可能是最常见的。

SESSIONS ENDS WHEN USER CLOSES THEIR BROWSER,

COOKIES END DEPENDING ON THE LIFETIME YOU SET FOR IT. SO THEY CAN LAST FOR YEARS

这是你选择的主要区别,

如果你想让id长时间被记住,那么你需要使用cookie;否则,如果你只是想让网站识别用户的访问,那么只有会话是可行的。

会话存储在php服务器将生成的文件中。为了记住哪个文件是针对哪个用户的,php还将在用户的浏览器上设置一个cookie,保存这个会话文件id,这样在用户下次访问时,php将读取这个文件并重新加载会话。

现在php默认每隔一段时间清除会话,并且会话的命名约定使其自动过期。此外,一旦浏览器关闭或历史记录被清除,浏览器将不会保留保存会话id的cookie。

值得注意的是,现在的浏览器还支持另一种存储引擎,如LocalStorage, SessionStorage和其他webdb引擎,javascript代码可以使用这些引擎将数据保存到您的计算机中以记住您。例如,如果你打开Facebook内部的javascript控制台,并输入“localStorage”,你会看到Facebook使用的所有变量来记住你没有cookie。