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!
简短的回答
按优先级排序的规则:
规则1。永远不要相信用户输入:cookie是不安全的。对敏感数据使用会话。
规则2。如果用户关闭浏览器时必须保留持久数据,则使用cookie。
规则3。如果用户关闭浏览器时不需要保留持久数据,则使用会话。
规则4。阅读详细的答案!
来源:https://www.lucidar.me/en/web-dev/sessions-or-cookies/
详细的回答
饼干
cookie存储在客户端(在访问者的浏览器中)。
cookie并不安全:读取和写入cookie内容非常容易。
在使用cookie时,您必须根据欧洲法律(GDPR)通知访问者。
过期时间可以设置,但用户或浏览器可以更改它。
用户(或浏览器)可以(被设置)拒绝使用cookie。
会话
Sessions are stored on the server side.
Sessions use cookies (see below).
Sessions are safer than cookies, but not invulnarable.
Expiration is set in server configuration (php.ini for example).
Default expiration time is 24 minutes or when the browser is closed.
Expiration is reset when the user refreshes or loads a new page.
Users (or browser) can (be set to) decline the use of cookies, therefore sessions.
Legally, you also have to notify visitors for the cookie, but the lack of precedent is not clear yet.
适当的选择
会话使用cookie!会话数据存储在服务器端,但UID存储在客户端cookie中。它允许服务器将给定用户与正确的会话数据匹配。UID是受保护的,很难被破解,但不是无懈可击的。对于敏感操作(更改电子邮件或重置密码),不要依赖会话或cookie:询问用户密码以确认操作。
敏感数据永远不应该存储在cookie(电子邮件、加密密码、个人数据……)请记住,数据存储在外国计算机上,如果计算机不是私有的(教室或公共计算机),其他人可能会读取cookie内容。
Remember-me数据必须存储在cookie中,否则当用户关闭浏览器时数据将丢失。但是,不要将密码或用户个人数据保存在“remember-me”cookie中。将用户数据存储在数据库中,并将此数据与存储在cookie中的加密ID /密钥对链接起来。
在考虑了前面的建议之后,下面的问题最终是什么可以帮助您在cookie和会话之间进行选择:
当用户关闭浏览器时,持久化数据必须保留吗?
如果答案是肯定的,请使用cookie。
如果答案是否定的,就使用会话。