Basics of Setting Cookies with PHP

Setting Cookies

A cookie is basically a text file located on the visitor’s computer used for various purposes by the website.

For instance, a cookie can hold your username for that website, and this is the example that this tutorial will be building on.

A cookie can be easily set using PHP’s setcookie() function:

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

The above shows how setcookie() should be used. First, you start the function by typing setcookie( , then you state the name of the cookie, the cookie’s value and expiration date.
Keep in mind that anything in the [] square brackets is optional, but it is always a good practice to include the expiration date, and you will obviously want a cookie value (unless the cookie is being deleted).

Ready to set a cookie?

<?php$name = “Mike”; setcookie(“username”,$name,time()+3600);?>

The code above sets a cookie called “username” with a value “Mike”, which will expire in 3600 seconds (or 1 hour).

Now that we have a cookie set, the logical thing to do would be to "read" it.

Since the cookie is named “username”, all we have to do to print out the value of the cookie is:

<?phpecho $_COOKIE[“username”];?>

Alternatively, you can use $name = $_COOKIE[“username”];, this way you can do anything you wish with $name.

As you can see, reading cookies is extremely easy.

The next page will tell you how to delete cookies and how to avoid common mistakes.

Deleting Cookies and Common Mistakes

Deleting cookies is very easy (don’t you just love the complexity of this all?): to delete a cookie, you must set a cookie with an expiration date in the past, and give that cookie an empty value.

No, we’re not going to teleport the cookie back in time, we’ll simply make the computer think that is already expired.
For example, this is the code to delete the “username” cookie that we set earlier:

setcookie (“username”, “”, time()-99999);

Note: The -99999 value can be any negative value you wish.

Common Cookie Mistakes

The most common mistake that people make is setting a cookie after there has been output, which is usually signified by an error similar to the following:

Warning: Cannot modify header information – headers already sent by (output started at /home/yoursite/public_html/setcookie.php:2) in /home/yoursite/public_html/setcookie.php on line 4

Take note that cookies are sent along with the page headers and therefore must be sent before any of the page is output! “Output” includes text, images and whitespace. This does not apply to reading a cookie, a cookie can be read from any point in the page.


You should now be able to do basic tasks involving cookies as well as be aware of their limitations.

Have fun!

About the Author: Kirill Talanov