When should I use session variables instead of cookies?

前端 未结 12 766
囚心锁ツ
囚心锁ツ 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:52

    Cookies are client-side, and sessions are server-side.

    Use cookies for small pieces of data that you can trust the user with (like font settings, site theme, etc.) and for opaque IDs for server-side data (such as session ID). Expect that these data can be lost at any time and they can not be trusted (i.e. need to be sanitized).

    Use session data for bigger data chunks (for many systems can store objects, data structures, etc.) and ones you have to trust - like authorization status, etc. In general, use session data for storing larger state data.

    You can store things like authorization status in cookies too, if it's needed for GUI, caching, etc. - but never trust it and never rely on it being present. Cookies are easy to delete and easy to fake. Session data is much harder to fake, since your application controls it.

提交回复
热议问题