Example 11: A very simple cookie

This is a very simple cookie example. A cookie is information that the browser sends to the server with every HTTP request. The server initially sends a cookie to a browser. The browser sends the cookie back with each request until the cookie expires. I will set, display, and unset a cookie. More details are available in the php setcookie() documentation.

Setting a cookie must be done before any output of the php file. This means that you must do this before the <html> tag. Cookies are set using the setcookie() function:

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

This means that you name the cookie, and optionally give it a string value, an expiration time, and other optional information. The simplest cookie would be:

setcookie( mycookie ) ;

This cookie will expire when the web browser is closed. This cookie can be used as a boolean value to determine if someone has visited a page. It doesn't store any information, but you can test for its existence. To test for its existence do something like:

if ( $_COOKIE["mycookie"] )
{
	// do stuff
}
else
{
	// do something else
}

A more powerful way to use cookies is to give them values and expiration times. You can set a value and expiration date like this:

setcookie( mycookie , "cookie value" , time() + 3600 ) ;

This cookie will expire one hour (3600 seconds) from the time it is set. The value stored in the cookie can be retrieved using $_COOKIE["mycookie"]. This can be set to a variable to use in your code.

You can also make cookies expire before the set time. This is done by setting the expiration time to a time in the past:

setcookie( mycookie , "" , time() - 3600 ) ;

It is a good idea to set the path and domain for a cookie so that it is only sent when it is needed. You should set the path to your directory on the web server, and the domain to the domain. This will prevent your cookies from being sent to someone else's page on the same server.

I have posted a simple demonstration of cookies with source code:

Cookies are sent with every HTTP request, so do not use them for sensitive information.



© 1996 -- 2005, Noel Schutt
E-mail me at: ski ihatespam at schutt dot org
(hint: delete " ihatespam " , and replace " at " with "@" and " dot " with ".")
Page last updated: 2004.04.16