Cookie basics
Cookies are small text files which are set by a server to the user's computer. They are extremely useful for storing information to improve your website's usability - things such as user options, settings and login details for when they return next time are a good example of the use of cookies.
In this tutorial we'll look at the basics of setting cookies using PHP and retrieving the data from them.
Setting a cookie
Setting cookies is handled by the unimaginatively named function setcookie. This function can take up to 7 parameters but as this is only a basics lesson we're only going to look at the 3 important ones which take the following syntax:
setcookie(cookie name, cookie value, expiry time)
Cookie name should be pretty straight forward - the name of the cookie.
Cookie value is a information to be stored in the cookie.
Expiry time is the time which the cookie will expire and be deleted from the client. In the PHP function this time is given by a unix timestamp which is discussed below.
Expiry time
The expiry time parameter is a unix timestamp. The current time as a unix timestamp is given by the function time(). To set the expiry time for a cookie we simply take this value and add as many seconds as required. If expiry is not given (it is an optional parameter) or is set to 0 the cookie will expire when the browser is closed.
An example
This PHP code will create a cookie called 'MyCookie' with a value of 'Hello World' set to expire in one week.
<?php
setcookie('MyCookie', 'Hello World', time() + (60*60*24*7));
?>
As described above the expiry time is calculated using the current value of time() added to the number until the date you wish for the cookie to expire. The amount of seconds is calculated as such:
60 seconds in a minute
60 * 60 seconds in an hour
60 * 60 * 24 seconds in a day
60 * 60 * 24 * 7 seconds in a week
Retrieving the data
Getting data from cookies is relatively easy using the superglobal $_COOKIE array:
<?php
echo $_COOKIE['MyCookie'];
?>
This will output the value of the cookie with the name 'MyCookie' like so:
Hello World
Debugging/List all cookies
To list all cookies set along with the data stored within them you can use the following PHP code which is helpful for debugging:
<?php
print_r($_COOKIE);
?>
This will output something similar to:
Array
(
[MyCookie] => Hello World
)
And that is cookies!
