Chapter 14. Cookies, Sessions, and Access Control

As your applications grow more complex, you’ll need to keep better track of your users. Cookies, sessions, and access control all provide an opportunity to interact appropriately with specific users. Sessions allow for the persistence of data in an otherwise stateless interaction. Without sessions, the web server sees each page request without the context of other page requests and therefore cannot remember data between requests.


You can track certain user details such as the number of visits, names, or the date of the last visit using cookies, small bits of text stored on the client that have been available since Netscape 1.0. The client machine stores this information and sends it to the web server whenever there is a request. Cookies data is sent along with the HTTP headers.

After the first visit to any web site, the browser returns a copy of the cookie to the server each time it connects. For security reasons, cookies can be read only from the domain that created them. Additionally, cookies have an expiration date after which they’re deleted. The maximum size of data that a cookie can hold is 4 KB.

Cookies are different from sessions because cookies are stored on the client’s disk, whereas a session stores the bulk of its data on the server. Sessions are basically like tokens, which are generated at authentication. This means that a session is available as long as the session hasn’t expired or the user hasn’t closed her browser ...

Get Learning PHP & MySQL, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.