Purpose Of PHP Sessions and Cookies and Their Differences

后端 未结 3 1092
梦如初夏
梦如初夏 2020-12-20 02:01

I am just starting to learn to program in PHP and have ran into a slightly confusing area, Sessions and Cookies.

I understand the server-side and client-side storage

3条回答
  •  爱一瞬间的悲伤
    2020-12-20 02:53

    The advantage of using cookies over sessions is that cookies are persistent.

    In other words, when the user visits your site weeks later, their session has more than likely expired. However, if they have a cookie that can uniquely identify them to your script, then you can automatically log them in and reestablish the session.

    ...what circumstances would each be appropriate for?

    The answer looks something like this:

    • Session data should contain information that does not need to be persistent or is only needed for a short period of time. For example, if you are presenting a multiple-page form to the user, it makes sense to take advantage of sessions.
    • Cookies should be used to store an ID or hash that uniquely identifies not only the user, but also the browser / device they are logged in with. Keep in mind that cookie data is out of your control and can only be manipulated / removed by HTTP requests made by the user (or under certain circumstances, by a script on a page).

    Also, i have seen people say that the cookie could be used to store a session id...

    I'm assuming what was meant by that is storing a unique value in a cookie that identifies the user / browser / device that they are using. Implementing something like this would look like:

    • Let the user log in as they would normally.
    • Generate a unique hash (SHA-1 is your best bet) and store that in a cookie. You also store the hash in a database linked to that user.
    • ...
    • The user returns after their session has expired and visits a page.
    • Your script sees the cookie and looks up the user that the hash belongs to.
    • The user is logged in.

提交回复
热议问题