Purpose Of PHP Sessions and Cookies and Their Differences

后端 未结 3 1091
梦如初夏
梦如初夏 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 03:02

    Both cookies and sessions are used to keep user-specific information in order to track a user. A lot of times you can use either one, but they have some differences.

    A cookie is a text file kept on the user's machine. Every time the users visits your site he hands over the cookie letting you know who he is. The advantage of this is that the information is kept on somebody else's machine so you don't have to worry about it. As such you can leave it there until the cows come home. When/if the user comes back he'll bring the information with him. The downside is that the information is out of your control because the user can easily edit the cookie you gave him. This makes any information in a cookie untrustworthy and has to be checked every time the user gives it to you.

    A session is like a cookie except you keep the information on your server. The advantage is that you can trust a session to keep data exactly like it was when you put it in. The downside is that you have to store that information which means that eventually you'll need to discard it lest your webserver fills up with information that will never be used.

    Now this is where it gets a bit tricky. You see while the mechanism of a session is as I described above, the actual implementation can vary depending on PHP's settings. The session data can be kept in individual text files or in a database on your server. Also you need some way of recognizing which session corresponds to which user. The usual (but not only) way to do this is with cookies. What happens is that the actual data stays on your server and is linked to a unique session id. That session id number is put on a cookie and given to the user so you can later look up his data when he comes back.

    The above process is performed automatically by PHP when you use the session functions; you do not need to implement it by hand. If for whatever reason you need to change how sessions are implemented you can do so by changing the session parameters in php.ini.

提交回复
热议问题