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.
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
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.