PHP Cookies – Background

Posted on May 3, 2011


Cookies have been around for quite some time on the internet. They were invented to allow webmaster’s to store information about the user and their visit on the user’s computer.

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!
PHP Code:

Don’t worry if you can’t follow the somewhat involved date calculations in this example. The important part is that you know how to set a cookie, by specifying the three important arguments: name, value and expiration date.
Retrieving Your Fresh Cookie

If your cookie hasn’t expired yet, let’s retrieve it from the user’s PC using the aptly named $_COOKIE associative array. The name of your stored cookie is the key and will let you retrieve your stored cookie value!
PHP Code:

This handy script first uses the isset function to be sure that our “lastVisit” cookie still exists on the user’s PC, if it does, then the user’s last visit is displayed. If the user visited our site on February 28, 2008 it might look something like this:
Your last visit was – 11:48 – 02/28/08

Posted in: PHP