Cookies and Sessions

Owing to the fact that HTTP is stateless - that is, any data you have stored is forgotten about when the page has been sent to the client and the connection is closed - it took a little work to find a solution to the problem. Eventually, Netscape put a solution into their browser known as "cookies" - tiny bits of information that a web site could store on the client's machine that were sent back to the web site each time a new 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, what they did on the site, and such, and many people believed that cookies signalled the end of privacy on the web. Urban myths popped up in many places saying that cookies can read any information from your hard drive, and people were encouraged to disable cookies across the board. The reality is, of course, that cookies are relatively harmless, and 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 - this cookie simply holds a value that uniquely identifies the client to the server, and corresponds to a data file on the server.

Topics covered in this chapter are:

  • How cookies and sessions compare

  • Which to use and when

  • How to use sessions

  • Using a database to store your sessions

  • Storing complex objects

Chapter contents

  1. 10.1. Cookies vs. Sessions
    1. 10.1.1. Cookies
    2. 10.1.2. Sessions
    3. 10.1.3. Choosing the appropriate option
  2. 10.2. Using cookies
  3. 10.3. Using sessions
    1. 10.3.1. Starting a session
    2. 10.3.2. Adding session data
    3. 10.3.3. Reading session data
    4. 10.3.4. Removing session data
    5. 10.3.5. Ending a session
    6. 10.3.6. Checking session data
    7. 10.3.7. Files vs. Databases
  4. 10.4. Storing complex data types
  5. 10.5. Summary
  6. 10.6. Exercises
  7. 10.7. Further reading
  8. 10.8. Next chapter

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Cookies vs. Sessions >>

Previous chapter: Next chapter

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.