Using Cookies

PHP

A cookie is a small piece of information that you ask a browser to remember for you. This is handy, since many people ma be visiting your site. For instance, you may want to "remember" a person's name, or some preference.
Later on, you can examine any cookies that you may have set, these will be in the PHP array $_COOKIE. ( see an example page)

By default, cookies expire (the browser removes them) when the browser is closed. If you set a time to expire, in the 3rd argument, the cookie will be kept until that time.
To "expire" a cookie, set a past time, such as time()-1.

Examples:

setcookie ("dog"); 	// cookie set, without a value

setcookie ("cat", $_GET['catsname']); // cookie set, with value from a form
setcookie ("horse","Seabiscit", time()+60*60*24*30); // expires in 30 days

print "The old cat name was: " . $_COOKIE['cat'];
 // previously set cookies will be in the COOKIE array

Important!  setcookie first

Cookies are sent to the browser in the http headers. This means that the php code for setcookie must be the very first thing in the file,  not even a space or any print statement.

Note that you will not receive the cookie until the next time a page is requested.

Avoid "Third party" cookies

A third party cookie is a cookie set, not by a page you browse to, but by a banner ad that is included in some page you visit. These are used by advertisers to build a profile of consumer preferences. You should consider setting your browser to not accept third party cookies.

Javascript for cookies

Cookies can also be accessed using javascript, as they are stored on the client. See Cookies in Javascript.


Lin Jensen.