Приглашаем посетить
Куприн (kuprin-lit.ru)

Section 10.1.  Cookies Versus Sessions

Previous
Table of Contents
Next

10.1. Cookies Versus Sessions

Both cookies and sessions are available to you as a PHP developer, and both accomplish the same task of storing data across pages on your site. However, there are differences between the two.

Cookies can be set to a long lifespan, which means that data stored in a cookie can be stored for months, if not years. Cookies, having their data stored on the client, work smoothly when you have a cluster of web servers, whereas sessions are stored on the server, meaning if one of your web servers handles the first request, the other web servers in your cluster will not have the stored information. Cookies can also be manipulated on the client side, using JavaScript, whereas sessions cannot.

Sessions are stored on the server, which means clients do not have access to the information you store about them. This is particularly important if you store shopping baskets or other information you do not want your visitors to be able to edit by hacking their cookies. Session data, being stored on your server, does not need to be transmitted with each page; clients just need to send an ID, and the data is loaded from the local file. Finally, sessions can be any size you want because they are held on your server, whereas many web browsers have a limit on how big cookies can be to stop rogue web sites chewing up gigabytes of data with meaningless cookie information. Sessions rely upon a client-side cookie to store the session identifierwithout this, PHP must resort to placing the identifier in the URL, which is insecure. If a cookie is used, it is set to expire as soon as the user closes his browser.

Cookies versus sessions usually comes down to one choice: do you want your data to work when your visitor comes back the next day? If so, then your only choice is cookies. If you are storing sensitive information, store it in a database and use the cookie to store an ID number to reference the data. If you do not need semi-permanent data, then sessions are generally preferredthey are a little easier to use, do not require their data to be sent in entirety with each page, and are also cleaned up as soon as your visitor closes his web browser.

Section 10.1.  Cookies Versus Sessions

Because cookies are stored on your visitor's computer, they can easily be changed by the visitor. This presents a serious security problem: if you store a user ID in a cookie to allow people to automatically log in when they visit your site, that user could edit the cookie to a different ID number and thus impersonate anyone. It's problems like this that make sesssions preferable for secure data; cookies are hard to secure without resorting to security through obscurity.



Previous
Table of Contents
Next