Chapter 10. Cookies and Sessions

HTTP is a stateless protocol, which means that any data you have stored is forgotten when the page has been sent to the client and the connection is closed. Eventually, Netscape invented the cookie—a tiny bit of information that a web site could store on the client's machine that was sent back to the web site each time the page was requested. Each cookie could only be read by the web site that had written it, meaning that it was a secure way to store information across pages.

Cookies earned a bad name at first, because they allowed people to track how often a visitor came to their site and what they did while there, and many people believed that cookies signalled the end of privacy on the Web. Urban myths popped up saying that cookies could read any information from your hard drive, and people were encouraged to disable cookies across the board. The reality is that cookies are harmless, and fortunately for us, are now commonly accepted.

Sessions grew up from cookies as a way of storing data on the server side, because the inherent problem of storing anything sensitive on clients' machines is that they are able to tamper with it if they wish. In order to set up a unique identifier on the client, sessions still use a small cookie that holds a value that identifies the client to the server, and corresponds to a datafile on the server.

Cookies Versus Sessions

Both cookies and sessions are available to you as a PHP developer, and both accomplish the same ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.