Cookies

A cookie, as already mentioned, is a tiny little file on your client's hard drive which contains data you have asked to be stored. Some clients specifically configure their browser to reject cookies, believing for one reason or another that they are malicious, and there is nothing you can do about this - that person's browser will not be able to store your data. When creating cookies, you specify how long you want it to be valid for, and, once done, the cookie remains in place until that date, when it "expires".

Author's Note: Are cookies dangerous? No, not at all - a web-site can only read data it stored, and it can only store a small amount of data. The only possible danger to cookies is that they can store information about you without you realising it - a web-site can track how often you visit, what times you visit at, what banners you clicked, etc. However, they cannot read your credit card number, raid your fridge, or anything of the sort!

Cookies are automatically sent to the web server (and received/parsed by PHP) each time a user visits you. That means that once we place our cookie, our visitors' browsers will automatically send the contents of that cookie across to us each time they view our messageboard index, and PHP will read the value into the $_COOKIE superglobal array. As cookies are sent each time, it is incredibly important not to store too much information there - they can really waste a lot of bandwidth.

The nice thing about cookies is that they are decentralised - you do not need to worry about creating databases to hold information or adding and removing rows, you just store the data and check whether it is set. As such, cookies are good for any pages where you have got a small amount of information to handle - usually this involves user preferences. For example, use cookies to store how users want their messageboard index sorting, what order they like their news printed, etc.

If you are storing information such as their email address, you should probably use a database - data like that is generally stored for long periods of time, whereas cookies are usually more throwaway information. That said, if you are storing personal information in cookies, please take the time to encrypt it.

 

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: Sessions >>

Previous chapter: Cookies vs. Sessions

Jump to:

 

Home: Table of Contents

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