Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - PHP

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Using Cookies - PHP

A cookie is a piece of information stored in a text file on a client’s computer to maintain information about the client during and between browsing sessions.

Using Cookies

 

A cookie is a piece of information stored in a text file on a client’s computer to maintain information about the client during and between browsing sessions. A website can store a cookie on a client’s computer to record user preferences and other information that the website can retrieve during the client’s subsequent visits. For example, a website can use cookies to store clients’ zip codes, so that it can provide weather reports and news updates tailored to the user’s region. Websites also can use cookies to track information about client activity. Analysis of information collected via cookies can reveal the popularity of websites or products. In addition, marketers can use cookies to determine the effects of advertising campaigns.

Websites store cookies on users’ hard drives, which raises issues regarding security and privacy. Websites should not store critical information, such as credit card numbers or passwords, in cookies, because cookies are typically stored in text files that any program can read. Several cookie features address security and privacy concerns. A server can access only the cookies that it has placed on the client. For example, a web application running on  www.deitel.com cannot access cookies that the website  www.prenhall.com has placed on the client’s computer. A cookie also has an expiration date, after which the web browser deletes it. Users who are concerned about the privacy and security implications of cookies can disable cookies in their web browsers. However, disabling cookies can make it impos-sible for the user to interact with websites that rely on cookies to function properly.

The information stored in a cookie is sent back to the web server from which it orig-inated whenever the user requests a web page from that particular server. The web server can send the client XHTML output that reflects the preferences or information that is stored in the cookie.

 

Writing Cookies

 

Figure 23.16 uses a script to write a cookie to the client’s machine. The cookies.html file displays an XHTML form that allows a user to enter a name, height and favorite color. When the user clicks the Write Cookie button, the cookies.php script (Fig. 23.17) exe-cutes.

 

 

1     <?xml version = "1.0" encoding = "utf-8"?>

 

2     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

3           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4              

5     <!-- Fig. 23.16: cookies.html -->

 

6     <!-- Gathering data to be written as a cookie. -->

 

7     <html xmlns = "http://www.w3.org/1999/xhtml">

 

8           <head>

 

9                  <title>Writing a cookie to the client computer</title>

 

<style type = "text/css">

11        body   { font-family: arial, sans-serif;

12                    background-color: #99CCFF }

13        form    { font-size: 10pt }

14        .submit { background-color: #F0E86C;

15                    color: navy;

16                    font-weight: bold }

17        </style>

 

18        </head>

 

19        <body>

 

20        <h2>Click Write Cookie to save your cookie data.</h2>

 

21        <form method = "post" action = "cookies.php">

 

22        <div>

 

                                   

23        <strong>Name:</strong><br          />        

24                    <input type = "text" name   =          "Name" /><br />

25                                           

26        <strong>Height:</strong><br         />

27                    <input type = "text" name   =          "Height" /><br />

28                                           

29        <strong>Favorite Color:</strong><br />

30                    <input type = "text" name   =          "Color" /><br />

31                                           

32        <input type = "submit" value = "Write Cookie"

33                    class = "submit" />              

34        </div>

 

35        </form>

 

36        </body>

 

37        </html>


Fig. 23.16 | Gathering data to be written as a cookie.

153   <?php

 

154     // Fig. 23.17: cookies.php

 

155     // Writing a cookie to the client.

 

156     extract( $_POST );

5

6           // write each form field’s value to a cookie and set the

 

7           // cookie’s expiration date

 

8           setcookie( "Name", $Name, time() + 60 * 60 * 24 * 5 );

 

9           setcookie( "Height", $Height, time() + 60 * 60 * 24 * 5 );

 

10          setcookie( "Color", $Color, time() + 60 * 60 * 24 * 5 );

 

11    ?><!-- end PHP script -->

12

13    <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

 

14    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

15          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

16

17    <html xmlns = "http://www.w3.org/1999/xhtml">

 

18          <head>

 

19                 <title>Cookie Saved</title>

 

20                 <style type = "text/css">

 

21                       body { font-family: arial, sans-serif }

 

22                       span { color: blue }

 

23                 </style>

 

24          </head>

 

25          <body>

 

26                 <p>The cookie has been set with the following data:</p>

27           

28                 <!-- print each form field’s value -->

 

29                 <br /><span>Name:</span><?php print( $Name ) ?><br />


 

 

30                 <span>Height:</span><?php print( $Height ) ?><br />

 

31                 <span>Favorite Color:</span>

 

32                 <span style = "color: <?php print( "$Color\">$Color" ) ?>

 

33                 </span><br />

 

34                 <p>Click <a href = "readCookies.php">here</a>

 

35                       to read the saved cookie.</p>

 

36          </body>

 

</html>


Fig. 23.17 | Writing a cookie to the client.

 

Script cookies.php (Fig. 23.17) calls function setcookie (lines 8–10) to set the cookies to the values passed from cookies.html. The cookies defined in function set-cookie are sent to the client at the same time as the information in the HTTP header; therefore, setcookie needs to be called before any XHTML (including comments) is printed.

 

Function setcookie takes the name of the cookie to be set as the first argument, fol-lowed by the value to be stored in the cookie. For example, line 8 sets the name of the cookie to "Name" and the value to variable $Name, which is passed to the script from cookies.html. The optional third argument indicates the expiration date of the cookie. In this example, we set the cookies to expire in five days by taking the current time, which is returned by function time, and adding the number of seconds after which the cookie is to expire (60 seconds/minute * 60 minutes/hour * 24 hours/day * 5 = 5 days). If no expi-ration date is specified, the cookie lasts only until the end of the current session, which is the total time until the user closes the browser. This type of cookie is known as a session cookie, while one with an expiration date is a persistent cookie. If only the name argument is passed to function setcookie, the cookie is deleted from the client’s computer. Lines 13–37 send a web page to the client indicating that the cookie has been written and listing the values that are stored in the cookie.

 

When using Internet Explorer, cookies are stored in a Cookies directory on the client’s machine, while Firefox stores them in a single file called cookies.txt. Figure 23.18 shows the contents of this directory (for a Windows XP and IE7 user harvey) prior to the execu-tion of cookies.php. After the cookie is written, a text file is added to the directory. In Fig. 23.19, the file harvey@localhost[1].txt appears in the Cookies directory. [Note: The name of the file created will vary from user to user.]


Reading an Existing Cookie

Figure 23.20 reads the cookie that was written in Fig. 23.17 and displays the cookie’s in-formation in a table. PHP creates the superglobal array $_COOKIE, which contains all the cookie values indexed by their names, similar to the values stored in array $_POST when an XHTML form is posted (see Section 23.4).

 

1          <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

 

2          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

3          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5          <!-- Fig. 23.20: readCookies.php -->

 

6          <!-- Displaying the cookie’s contents. -->

 

7          <html xmlns = "http://www.w3.org/1999/xhtml">

 

8          <head>

 

9          <title>Read Cookies</title>

 

10        <style type = "text/css">

 

           

11        body   { font-family: arial, sans-serif }

12        table   { border-width: 5px;

13                                border-style: outset }

14        td         {           padding: 10px }

15        .key     {           background-color: #F0E68C }

16        .value { background-color: #FFA500 }

 

17        </style>

 

18        </head>

 

19        <body>

20        <p>

 

21        <strong>The following data is saved in a cookie on your

22        computer.</strong>

23        </p>

 

24        <table>

 

25        <?php

 

                                               

26        //          iterate through          array $_COOKIE and print

27        //          name  and value      of each           cookie

28                    foreach          (           $_COOKIE as $key => $value )   

29                                print(   "<tr><td class =         'key' >$key</td>       

30                                <td       class =            'value' >$value</td></tr>" );

31        ?><!-- end PHP script -->

 

32        </table>

 

33        </body>

 

34        </html>


Fig. 23.20 | Displaying the cookie’s contents

 

Lines 28–30 iterate through the $_COOKIE array using a foreach statement, printing out the name and value of each cookie in an XHTML table. The foreach statement takes the name of the array ($_COOKIE) and iterates through each index value of the array ($key). In this case, the index values are the names of the cookies. Each element is then stored in variable $value, and these values become the individual cells of the table.

 

We could have also used the function extract to create individual variables out of the key-value pairs in $_COOKIE, just as we did with $_POST. For example, after the function extract( $_COOKIE ) is called, the value of a cookie set with the name "Color" is assigned to variable $Color. Try closing your browser and revisiting readCookies.php to confirm that the cookie has persisted.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.