PHP 5 Cookies

A cookie is a little piece of information sent between the server and the client, which is most often a webbrowser. You can instruct the webbrowser to save your information and later retrieve it from the browser again. This allows you to save information about your visitors, for instance preferences or statistical information. A very common usage of cookies is to see whether or not a certain person has visited the site before, usually within a defined range of time, to tell whether the user should be counted as a new visitor or a returning visitor. Information like this is used for statistics, for instance a counter.

PHP can instruct the webbrowser to save a cookie by using the setcookie() method. Of course, the webbrowser can fail to do so for several reasons, for instance because the user has said no to cookies, but most modern webbrowsers will save the cookie for you. The setcookie() method allows you to define how long the cookie should be saved for and which path and domain it should be valid for.

Now let's look at a more complete example of how cookies can be used. First some code, then an explanation of it all:

Example -

Modify a Cookie Value

Example -

Delete a Cookie

To delete a cookie, use the setcookie() function with an expiration date in the past:

Example -

Check if Cookies are Enabled

The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:

Example -