Creating and Reading from Cookies

I l @ ve RuBoard

The most important thing to understand about cookies is that they must be sent from the server to the client prior to any other information. Should the server attempt to send a cookie after the Web browser has already received HTML, even an extraneous white space, an error message will result and the cookie will not be sent (Figure 12.2). This is by far the most common cookie- related error.

Figure 12.2. This friendly and informative message is what you'll see if the setcookie() function is called after anything, even a blank line, has already been sent to the Web browser.

graphics/12fig02.gif

Cookies are sent using the setcookie() function:

 setcookie ("name", "value"); 

That line of code will send a cookie to the browser with a name of name and a value of value (Figure 12.3).

Figure 12.3. If the user has the "Warn me before accepting a cookie" box checked in their Preferences (Figure 12.1), a prompt like this will appear for each cookie sent.

graphics/12fig03.gif

You can continue to send more cookies to the browser with subsequent uses of the setcookie() function, although you are limited by Web protocols to sending at most 20 cookies from one server to one user:

 setcookie ("name2", "value2"); setcookie ("name3", "value3"); 

To retrieve a value from a cookie, you only need to refer to the cookie name as a variable (the name preceded by a dollar sign), just as you would refer to an HTML form element as a variable on the handling page. For example, to retrieve the value of the cookie established with the line setcookie ("UserName", "Larry"); you would use the variable $UserName.

For an example of setting cookies, let's create a page that allows the user to specify the text and background colors of a page.

To send and retrieve cookies with PHP:

  1. Create a new PHP document in your text editor by beginning with the standard opening PHP tag (Script 12.1).

     <?php 
    Script 12.1. Two cookies will be used to store the user's choices for the background and text colors. The form-submitted values will also be assigned to the page so that the requested change is applied immediately.

    graphics/12sc01.jpg

    graphics/12sc01a.gif

  2. Write a conditional that will send the cookie if the form has been submitted.

     if ($BeenSubmitted) { 

    Just as you've done before, the $BeenSubmitted variable will be used to determine whether or not the form has been submitted. If TRUE, then the PHP will process the form.

  3. Set the cookies and then colors for the page itself.

     setcookie("BGColor",      "$NewBGColor");     setcookie("TextColor",      "$NewTextColor");     $BGColor = $NewBGColor;     $TextColor = $NewTextColor; 

    If the form has been submitted, the PHP will send two cookies with the values for the background and text colors. The script will then set the current values ($BGColor and $TextColor) to the preferred values ($NewBGColor and $NewTextColor) in order to reflect the change immediately.

  4. Finish the conditional.

     }else{    if (!$BGColor) {        $BGColor = "WHITE";    }    if (!$TextColor) {        $TextColor = "BLACK";    } } 

    If the form has not been submitted, the PHP will check to make sure that the background and text colors have not been assigned. If they have not been, they'll be assigned default values.

  5. Close the initial PHP section then create the HTML head.

     ?> <HEAD> <TITLE>User Customization</TITLE> </HEAD> 
  6. Establish another PHP section to print out the <BODY> tag with the proper values for the background color and text color .

     <? print ("<BODY BGCOLOR=$BGColor  TEXT=$TextColor>\n"); ?> 
  7. Print a simple sentence that will reveal the text color.

     Currently your page looks like this! 
  8. Create an HTML form that will be submitted back to itself.

     <FORM ACTION="cookies.php"  METHOD=POST> 
  9. You could also have PHP print the value of $PHP_SELF which always refers to the page.

  10. Make two pull-down menus for the user to select the background and text colors.

     Select a new background color: <SELECT NAME="NewBGColor"> <OPTION VALUE=WHITE>WHITE</OPTION> <OPTION VALUE=BLACK>BLACK</OPTION> <OPTION VALUE=BLUE>BLUE</OPTION> <OPTION VALUE=RED>RED</OPTION> <OPTION VALUE=GREEN>GREEN</OPTION> </SELECT> Select a new text color:  <SELECT NAME="NewTextColor"> <OPTION VALUE=WHITE>WHITE</OPTION> <OPTION VALUE=BLACK>BLACK</OPTION> <OPTION VALUE=BLUE>BLUE</OPTION> <OPTION VALUE=RED>RED</OPTION> <OPTION VALUE=GREEN>GREEN</OPTION> </SELECT> 

    Each pull-down menu only gives 5 options, in word form. You can add more choices to these menus, if you want, as long as you restrict yourself to the valid HTML colors.

  11. Code for a hidden variable that will indicate whether or not the form has been submitted.

     <INPUT TYPE=HIDDEN  NAME=BeenSubmitted VALUE=TRUE> 
  12. This is the variable that will tell the script that the form has been submitted.

  13. Add the submit button, then close the form and the HTML page.

     <INPUT TYPE=SUBMIT NAME="SUBMIT"  VALUE="Submit!"> </FORM> </BODY> </HTML> 
  14. Save the page as cookies.php, load it to the server, and test in your Web browser (Figures 12.4, 12.5, 12.6, 12.7 and 12.8).

    Figure 12.4. Upon first coming to cookies.php, the page looks like this with the default colors being used: a white background and black text.

    graphics/12fig04.gif

    Figure 12.5. This is the message the user will see when the first setcookie() call is made if they have opted to be warned before accepting a cookie. This cookie is storing the value of BLUE in a cookie named BGColor.

    graphics/12fig05.gif

    Figure 12.6. The second cookie that gets sent is called TextColor and has a value of WHITE. If the "Warn me before accepting a cookie" box is not checked in the user's preferences, they will not see these messages.

    graphics/12fig06.gif

    Figure 12.7. Upon receiving the values from the HTML form, the cookies.php page will send the two cookies to store the information and then reflect the changes in the page.

    graphics/12fig07.gif

    Figure 12.8. By viewing the source code of the page, you can also track how the color values change.

    graphics/12fig08.jpg

Tip

The value of a cookie is automatically urlencoded when it is sent and urldecoded upon being received by the PHP page. As you know, the same is true of values sent by HTML forms.


Tip

It is important to remember that the value of a cookie will always take precedence over values passed by a form. In cookies.php, for example, if the form inputs were named BGColor and TextColor you would have problems because the BGColor and TextColor cookies would override the form values.


I l @ ve RuBoard


PHP for the World Wide Web (Visual QuickStart Guide)
PHP for the World Wide Web (Visual QuickStart Guide)
ISBN: 0201727870
EAN: 2147483647
Year: 2001
Pages: 116
Authors: Larry Ullman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net