Cookies are bits of data that a web browser stores on your visitor's computer. They can be very useful if you need to store things like your visitor's preferences or login data (if your site has a membership facility) or other things that are specific to a particular visitor. This tutorial teaches you how you can set cookies, retrieve them and delete them using PHP.
This tutorial assumes that you already know how to write scripts in PHP. You don't have to be an expert, but some working knowledge is necessary or you will not be able to follow the discussion.
Setting a cookie with PHP could not be easier, since PHP provides a function for you to do precisely that. The following code sets a cookie called "userlogin" with a value of "anonymous":
The code starts by calculating the expiry date of the cookie. Cookies have a limited lifespan. If you do not
set an expiry date, the cookie will expire automatically when the user closes his/her web browser. The expiry date
has to be in a special format, so it's actually simplest to just use the
time() function and work from
there. This function returns the current date and time in the required format.
My code adds 60 seconds to the existing time, effectively making the cookie last for only 1 minute.
The second line calls the
setcookie() function, which does the actual work of setting the cookie
in PHP. This is a built-in function in PHP. The first parameter (or argument) to
the name that you want to give the cookie. It can be any name you like. In the example above, I gave
the cookie the name "userlogin".
The second parameter to the
setcookie() function contains the actual data that you want saved.
Again, this can be any data you like, although the maximum size of any cookie is 4 KB. This 4 KB includes things
like the date of expiry, the name, and other cookie overheads, so you don't really have all 4,096 bytes to work
with. Note that cookies are not encrypted by default, so unless you encrypt your data yourself, you should not
store any sensitive information in them.
The third argument is the date of expiry that was calculated earlier. As noted earlier, my code gives
the cookie a very short lifespan. If you want your cookie to last longer, and you surely will,
you will have to add the lifespan you want, converted to seconds, to the value returned by
Here's an example of how to do that using a new variable,
$number_of_days variable to the number of days you want your cookie to last, and the code
below will calculate the actual date of expiry for you in a format suitable for passing to the
You will of course have to pass
setcookie() as its third parameter.
Although the above parameters to
setcookie() are probably the most useful, there are additional
parameters that you can use when calling the function. These parameters are optional, and can be omitted if
you don't need to use them.
As it stands, the cookie set in the above example will only be valid for the directory (or folder) where the
current web document is kept as well as its descendant directories. For example, if your script was executed
from the page
then the cookie will be valid for any file in
http://www.example.com/members-only/ and the subdirectories below it.
If you want your cookie to be valid for every folder on your website, you will have to specify a fourth argument to
The fourth parameter should be the top directory where you want to cookie to be available in. If it is set to "/" (the root folder of your website) as in the above example, it will be valid throughout your site. If you want the cookie to be available only in the "/secret" directory, pass "/secret" instead of "/" to the function.
If your cookie was set for a user accessing your site using (say)
http://www.example.com, the cookie will not be valid if he/she goes
example.com even if both URLs resolve to the same site. To make it valid no matter which subdomain name of example.com is used,
you will need to add a fifth parameter to
Note that if you add a fifth parameter to the function, you must include the fourth parameter — that is, the path or folder argument will no longer be optional. However, if you don't really want to set the fourth parameter but only the fifth, you can pass an empty string (that is, "") for the that parameter.
Since cookies are sent by the script to the browser in the HTTP headers, before your page is sent, they
must be set before you even send a single line of HTML or any other page output. The moment you send
any sort of output, you are signalling the end of the HTTP headers. When that happens, you can no longer set any cookie.
If you try, the
setcookie() function will return FALSE, and the cookie will
not be sent. You will probably also get a PHP error message.
setcookie() returns TRUE, the cookie was successfully sent to the web browser. This does not
mean that the cookie has been successfully set, though, since it's possible that the user has disabled cookie support.
However, where the PHP interpreter is concerned, the cookie has been sent.
There are other, less-used parameters for
setcookie(). For the full documentation, please see the
PHP manual page for setcookie().
Cookies set for a page can be retrieved from the variable
$_COOKIE['cookie_name'] where 'cookie_name'
is the name of the cookie you set earlier.
For example, if you wanted to display the value of the "userlogin" cookie, the following code should do the trick.
Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:
Remember that cookies are sent in the HTTP headers, both to and by the web browser. At the time
the above script runs, the web browser will have sent a request to your server for your script without including
any "userlogin" cookie, since none has been set yet (unless one was already set in an earlier session).
As such, when the PHP interpreter loads your script, it will create the
$_COOKIE array without
your "userlogin" cookie.
(Sites that want to check whether a cookie is successfully set are typically those that depend heavily on cookies to deliver content, such as those that only show certain pages to members paying a subscription fee. Since they require that a login cookie be present, they may want to check to see if cookie support has been disabled in the browser and warn the user if so. The most reliable way to perform such a check, at this time, is to set a cookie and then try to retrieve it.)
Cookies can also be deleted. This is useful for situations such as when a user logs out of your site. To delete a cookie,
setcookie() function again with the same name, folder and domain that you used earlier to set
the cookie. However, instead of an expiry date set in the future, this time give an expiry date some time in the past.
The above code simply sets the expiry date 60 seconds in the past, effectively making the cookie no longer valid.
That's it. Armed with the above information, you are well on your way to creating PHP code that can set, retrieve and delete cookies.
Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at http://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.
This article is copyrighted. Please do not reproduce this article in whole or part, in any form, without obtaining my written permission.
It will appear on your page as: