Cookies in PHP

I got most of the information from the Sessions and Cookies by O'Reilly Media. I also found the information from the book on this general topic to be most insightful. Previous to doing this weeks assignment I knew what cookies were but I did not know how they were made and inplemented.


In php a cookie is a name/value pair association with a given website, and store on the computer that runs the cliente. A cookie can store most any information that is needed. Some of this information can be: whether you are logged in, what is in the shopping cart, or if you need to registrar. This is very useful to make our webpages more functional. The code for a cookie can be very simple.

setcookie('mycookie', 'somevalue', time() + 3600 * 24 *365;

The setcookie function is very versatile, technically only the first field, the name, is required. The expirytime of the function was most interesting to me. The function is set up to to specify when the cookie will expire on the computer. This is done by specifying how long it should stay alive in seconds from January 1, 1970. If this time is not included the cookie will expire when the browser is closed.

Life Cycle of a cookie

The book gives a good explanation of the steps in which a cookie is made and used. There are 5 basic steps that constitute the majority of the life of a cookie. They cover creation and implementation. I will try and give a more simple decription than the book to simulate working with a cliente that wants to know about cookies.

  1. The cookie is set up when the web browser requests a webpage that is set up to make cookies.
  2. The webpage is sent back to the web browser with the instructions on how to make the cookie.
  3. When the browser receives the webpage the cookie is created and stored as it was setup.
  4. When any return trips are made to the same webpage the information in the cookie will be sent along with it.
  5. The web server receives the cookie and can process the information contained in it.

Working Example / References

This is a hard one to show a working example of on the web. I did take the time to look through the cookies that are on my computer. I was amazed how hard it was to find them. I had to change two different file viewing options just to see where they were. I could not find any of they had anything that could be read, but I was surprised at how many of them there were. It was interesting to see just how many of the site that I go to use the cookies.