When should I use session variables instead of cookies?

前端 未结 12 732
囚心锁ツ
囚心锁ツ 2020-12-07 11:12

Session variables and cookies seem very similar to me. I understand the technical differences, but how do you decide when to use one vs. the other?

12条回答
  •  借酒劲吻你
    2020-12-07 11:39

    Sessions and cookies are not the same at all. Cookies are client side. Sessions are server side. Sessions often (but not necessarily) use cookies to correlate one request with another from the same user to identify that they belong to the same session.

    A session is an artificial concept, and HTTP doesn't have that notion. It is created by web servers to help web developers carry information across requests, like user account information, shopping carts, form data, etc. A cookie is carried by standard HTTP headers.

    The information you store in a session vs. a cookie is up to you. Typically you put stuff in cookies that you want to persist across sessions after the user closes his/her browser. Maybe remembering authentication tokens to implement "remember me" functionality, or past user activity to personalise his/her experience. Keep this information small and "referential", i.e. it could be just IDs that refer to richer information you store sever side. Remember that what is client side is more vulnerable to malware, so don't store passwords or sensitive information.

    Finally, there is also local storage, which you did not mention. This is also client side, but arguably a bit less susceptible to cross-site scripting hacks since, unlike cookies data, it is not automatically sent in the headers.

提交回复
热议问题