At first they were feared by the general public because it was believed they were a serious privacy risk. Nowadays nearly everyone has cookies enabled on their browser, partly because there are worse things to worry about and partly because all of the "trustworthy" websites now use cookies.
This lesson will teach you the basics of storing a cookie and retrieving a cookie, as well as explaining the various options you can set with your cookie.
Creating Your First PHP Cookie
When you create a cookie, using the function setcookie, you must specify three arguments. These arguments are setcookie(name, value, expiration):
- name: The name of your cookie. You will use this name to later retrieve your cookie, so don't forget it!
- value: The value that is stored in your cookie. Common values are username(string) and last visit(date).
- expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.
In this example we will be creating a cookie that stores the user's last visit to measure how often people return to visit our webpage. We want to ignore people that take longer than two months to return to the site, so we will set the cookie's expiration date to two months in the future!