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. However, in its most simple form, the setcookie() method is used like this:

setcookie("user_name", "John Doe");

The first parameter is the name of the cookie, and the second is the value. In this case we store a cookie with the name "user_name", with a value of "John Doe". The value can be retrieved again by using the $_COOKIE superglobal, like this:

echo $_COOKIE["user_name"];

You should be aware that the setcookie() method is a header related function, which means that it has to be called before any output is made to the browser (including text, HTML tags and so on) and that the value you set can't be read until next time the page is loaded, which just means that you can't save a cookie and read the value in the same page execution. As mentioned, you can define for how long a cookie should be stored.

The third (and optional) parameter for setcookie() is used for this. If no parameter is supplied, or if it has been set to 0, the cookie will expire when the session ends, which typically is the same as when the browser is closed. Otherwise you should define the time when the cookie should expire, with a Unix timestamp. Here's an example where we set a cookie that will last for 1 hour:

setcookie("user_name", "John Doe", time() + 3600);

We use the time() method to get the current time as a Unix timestamp and then we add an hour, which is the same as 3600 seconds.

Now let's look at a more complete example of how cookies can be used. First some code, then an explanation of it all:
<?php
if(isset($_GET["color"]))
{
    setcookie("color", $_GET["color"]);    
    header("Location: " . $_SERVER["PHP_SELF"]);
}

if(isset($_GET["reset"]))
{
    setcookie("color", "");
    header("Location: " . $_SERVER["PHP_SELF"]);
}

if(isset($_COOKIE["color"]))
{
    echo "Your favorite color is: " . $_COOKIE["color"] . "<br />"; 
    echo "<a href=\"?reset=1\">Click here to reset</a>";
}
else
{
    echo "What's your favorite color?<br /><br />";
    echo "<a href=\"?color=red\">Red</a>&nbsp;&nbsp;";
    echo "<a href=\"?color=green\">Green</a>&nbsp;&nbsp;";
    echo "<a href=\"?color=blue\">Blue</a>&nbsp;&nbsp;";
}
?>
Okay, lots of lines here, but it's not too complicated though. With the first if statement, we check if the color has been set in the query string. This happens when we click on one of the links that we output later. If a link has been clicked, it means that the user has made a favorite color decision and we then call the setcookie() method to save it. After that, we perform a little trick, to make sure that the user choice is reflected immediately: We do a redirect to the current, basically a reload of the page, using the header() method with the Location heder. You don't have to completely understand this part, just know that we do it to be able to read the cookie immediately - otherwise the user would have to manually reload the page to see their choice reflected.

Since we also offer a reset option, we check for the reset parameter. If it has been set, the user wants to delete their previous choice and therefore we set a cookie with the same name, but with an empty value. This is the same as deleting the cookie. After that, we do the same redirect trick as described above.

After that, we finally get to the part where we check whether a cookie has been set or not. If it has, we remind the user which choice they made and then offer them a chance to reset it. If it hasn't been set, we ask the user which color is the favorite and then output some options to click on, which will activate the cookie setting code as first described.

If this seems overwhelming, just try running the example a couple of times and then return to have a look at the code - it's actually quite simple.
<PreviousNext>
^ Back to Top