Putting a Cookie in Your Site

Now it is time to put your knowledge into action. We are going to develop a couple pages with cookies, starting off with the one described earlier, which allows the user to enter a name on the form, which the web page remembers for a long period of time. The first thing we need to do is develop an HTML document. This HTML form allows the user to enter his name. From there, we will develop a couple of PHP forms that display the user’s name.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Developing a page with cookies</title>
</head>

<body>
Please enter your name into the following text box and hit submit. Note that if
  you have entered in a name in the past few weeks, that name will be deleted with
  the new one.
<p>
<form name="cookie" action="phpft12-01.php" method="post">
Enter your name here:
<input type="text" name="name" />
<p>
<input type="submit" />
</form>

</body>
</html>

This is a very simple page, with just an input textbox. The page ends up looking like Figure 12.1. You can see this file on the CD as phpft12-01.html.

Figure 12.1. The phpft12-01.html file.


Let’s enter a name in that box. You press submit, and what do you get? Nothing yet, because we still need to design the PHP page. Let’s do that now. We want this PHP acceptor to do a couple of things:

  • It should confirm whether a cookie has been created recently. If it has, then we need to delete that cookie and reset it with the new value. If not, it simply needs to create the new cookie.

  • It should direct the user to a new page, which shows the cookie results. If the cookie is valid, it will say the user’s name; if invalid, the page will say that a cookie has not been set.

The PHP page is a little complex, so let’s go through it one step at a time. Then, we will look it over all at once so you can see how everything flows. The first part of the script tests to see if the user left the field from the form page blank or did not access the PHP page through the form:

<?php
$cookievalue = $_POST['name'];
//if cookievalue is blank, end the page
if ($cookievalue == '')
    {
       echo "You did not submit a cookie value. Please go back to
<a href="phpft12-01.html"> phpft12-01.html</a> and correct this error.";
       exit;
}

This section assigns the value of the form to the variable $cookievalue. It then tests to make sure $cookievalue has a value. If it is blank, a statement is echoed referring the user to go back to the form page and submit the form.

Note the following statement: exit. It uses a language construct exit. This construct should be used if there is an error—it halts execution of the PHP script in the web page and causes the page to skip over any further PHP. When you have an error such as this one, you can use exit to tell the browser that an error has occurred.

It’s important to note that some PHP programmers prefer that you never use exit(), because it breaks the flow of the program. If you want the web page to completely load whether or not there is an error, you should not use exit(). The best time to use exit() is when the error is fatal, and you do not want the program to continue to execute without it.

After this section, we have another that checks to see if a cookie has been set recently, depending on the cookie length:

//If the cookie has been set recently
if (isset($_COOKIE['name']))
   {
          setCookie("name", "", time()-1);
       unset($_COOKIE['name']);
   }

Here, we use two new functions to see if a cookie has been created. isset() returns true if its parameter (in this case, the name cookie) has been set. If the cookie was set, we delete the cookie by resetting it to expire in the past, and then we use the unset() function to delete the cookie from the $_COOKIES array. Why do we reset the cookie with the setCookie() function? We have to redefine the cookie to delete it, because no function directly deletes it. Instead, we use the setCookie() function to delete it by creating a cookie with the same name that expires in the past (time()-1). The cookie is automatically deleted by the web browser.

The last step is to create the cookie:

//Whether or not the cookie was set earlier, set this cookie.
setcookie("name", $cookievalue, time() + 60 * 60 * 24 * 12);

echo "Cookie has been set, please visit
<a href="phpft12-01result.php">phpft12-01result.php</a> to see the result.";

?>

We set the cookie to last 12 days by giving it an expire time of time() + 60 * 60 * 24 * 12, and we set the value to the name that was submitted on the form. Remember that you are creating stored bits of data that exist for a set amount of time, so the amount of time we use for the cookies is the time the cookie will exist.

Now, we put this in the web document after the <body> tag, and the script should execute flawlessly, right? Check out what happens when we do this by looking at Figure 12.2.

Figure 12.2. An error with the phpft12-02.php file.


Uh oh. We got an error! What happened? When creating cookies, you have to put the cookie before any HTML tag. Cookies are part of a special part of the document which is dealt with before even the <html> tag. You need to set them before even the opening <html> tag. If you have any <!DOCTYPE> or <meta> tags, the cookie must go before these, also. This means that you cannot create a cookie after any executed echo statement in your program.

By rearranging the document so it looks like the following, we can get a better result:

<?php

$cookievalue = $_POST['name'];
//if cookievalue is blank, end the page
if ($cookievalue == '')
    {
       echo "You did not submit a cookie value. Please go back to
<a href="phpft12-01.html"> phpft12-01.html</a> and correct this error.";
       exit;
    }

//If the cookie has been set recently
if (isset($_COOKIE['name']))
   {
       unset($_COOKIE['name']);
   }

//Whether or not the cookie was set earlier, set this cookie.
setcookie("name", $cookievalue, time() + 60 * 60 * 24 * 12);

echo "Cookie has been set, please visit <a href="phpft12-01result.php">
  phpft12-01result.php</a> to see the result.";

?>

<html>
<head>
<title>Creating the cookie</title>
</head>

<body>

</body>
</html>

We moved the PHP code above the <html> section. Notice that the body is empty. This doesn’t matter: The cookie will still set and everything will work fine. Figure 12.3 shows the result.

Figure 12.3. Finally setting a cookie in phpft12-01.php.


Now all we have to do is create a simple PHP page that echoes out the cookie. This isn’t too bad at all. Check out the following source from phpft12-01result.php on the CD:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Displaying the cookie</title>
</head>

<body>

<?php

$cookievalue = $_COOKIE['name'];
//if the cookie is blank or does not exist, echo an error
if ($cookievalue == ")
    {
        echo "You have not created the cookie yet? Go to
   <a href="phpft12-01.html">phpft12-01.html</a> to set a cookie.";
        exit;
    }
else
    {
        echo "Welcome back to the page, $cookievalue. Feel free to change your
cookie by visiting <a href="phpft12-01.html">phpft12-01.html</a>.";
    }
?>
</body>
</html>

This page simply echoes an error if the cookie does not exist and displays the person’s name if it does exist.

Let’s see the three pages in succession. Figure 12.4 shows how a person can enter his name, Figure 12.5 shows the result of entering a name, and Figure 12.6 shows the final results.

Figure 12.4. Step one: entering your name.


Figure 12.5. Step two: creating the cookie.


Figure 12.6. Step three: the results.


Check that out! Three steps to set a complete cookie and display it on one page.

I have an exercise for you: Rewrite these PHP pages so that it does all three of these steps on one page. Make one page display a form, set the cookie, and echo the result out if it exists. This is a pretty tough job, but I bet you are up to it!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.15.248