On the CD The quiz and origami store examples contain practical uses of cookies and session variables and are described in the next chapters. In Chapter 16, “Scaling Up Your Application,” you will read about using session variables to implement a password system. In this chapter, the examples are short and designed to encourage you to implement them and try them in various combinations. The scripts explained here show the use of cookies and sessions. The CD-ROM contains the code for the projects in the folder named chapter13code.
The setting of cookies is independent of ASP versus PHP, but not independent of a browser. The examples described here all make use of a form in which the user enters a name and a type of [dessert] cookie. Examples of cookies are things you eat, such as chocolate chips or lemon squares. Two computer cookies are set when the form is submitted: one named ‘cname’ for the username, and the other named ‘type’. The scripts cookies.asp and cookies.php each set the two cookies to persist only as long as the browser is open. The scripts cookies5min.asp and cookies5min.php each set the cookies to last for five minutes. The time interval of five minutes was chosen to give you enough time to exit the browser or go to another Web site, but not too long to try your patience. The intent is for you to perform two tests for each of the four scripts:
Execute the script, exit the browser, and then invoke the same browser again within five minutes.
Execute the script, do something else for more than five minutes, and return to the page of the script. You might need to force the browser to reload the page, which sometimes is a problem.
In the first case, the values of the cookies the name and the type of cookie, will not appear if the script last used was cookies.asp or cookies.php. The two values will appear if the script was cookies5min.asp or cookies5min.php. In contrast, if you invoke one of the five-minute scripts first and then cookies.asp or cookies.php, you will see the last set of values. The form is shown in Figure 13.6.
Figure 13.6: Form to enter information to be stored as cookie. Web browser 2003 Netscape
Filling in the cookie, you will see something like what is in Figure 13.7.
Figure 13.7: Form filled in.
Clicking on the send info button will produce the response Web page in Figure 13.8.
Figure 13.8: Response to form.
Now we will examine the scripts for these pages. The first pair of scripts (one for ASP and one for PHP) produce cookies that last only as long as the browser is open. These are called cookies without expiration. This terminology does not mean that they never expire; it means, again, that they last as long and only as long as the browser is open. The second set of scripts sets an expiration time for the cookies. The expiration time chosen is quite short: five minutes. However, it is not associated with the running of the browser.
The cookies.asp script, shown in Table 13.1, both handles the form data and displays the form for the user to enter data.
<%@ Language=JavaScript %> | Sets JavaScript as language |
<% | Starts ASP |
var submitted=String(Request.Form("submitted")); | Extracts submitted form data |
if (submitted !="undefined") { | Checks if form has been filled out |
sname=String(Request("cname")); | Set variable with form data |
stype=String(Request("type")); | Set variable with form data |
Response.Cookies("ccname") = sname; | Define cookie named “ccname” (or, to use the collection terminology, with the key “ccname”) to be the value of sname |
Response.Cookies("ctype") = stype; | Define cookie named “ctype” (key “ctype”) to be the value of stype |
%> | Close ASP |
<html><head><title>Use cookie </title></head> | Normal HTML start |
<body> | HTML body tag |
<h1> Welcome | HTML |
<% | Start ASP |
Response.Write (sname + "</h1>\n"); | Write out information given by form |
Response.Write ("<br>You like "+ stype +" cookies."); | Write out information given by form |
%> | Close ASP |
<body> | HTML |
</html> | HTML |
<% } | Restart ASP to close off true if clause |
else { %> | Start else clause and close ASP |
<html><head><title>Form for cookies</title></head><body> | Normal HTML |
<form action="cookies.asp" method=post> | Start form. Action handler is this script |
Your name <input type=text name='cname' value='<%fromcookiename= Request.Cookies("ccname"); | Input tag. This code will display the customer name data if it has been stored as a cookie. A local variable is used to hold the value |
Response.Write(fromcookiename);%>'> | The variable is sent to the browser. If there was no cookie sent, nothing will be displayed |
<br> | Line break |
Your favorite cookie <input type=text name='type' | Input tag |
value='<%fromcookietype=Request.Cookies("ctype");Response.Write(fromcookietype); %>'> | A local variable is set with the value from the cookie and written out |
<br> | Line break |
<input type=hidden name='submitted' value=TRUE> | Input tag for hidden value to indicate the form has been submitted |
<input type=submit value='send info'><input type=reset value='reset'> | Input tag for the submit button |
</form> | Form closing tag |
</body> | Body closing tag |
</html> | HTML closing tag |
<% } %> | Restart ASP to close Else clause |
The cookies.php, shown in Table 13.2, follows the same overall structure as the ASP file for the form handler and form. For the PHP case, you need to use the @ operator to suppress an error message in the case when no variable, including no cookie, exists.
<?php | Start PHP |
if (@($submitted)) { | Check for is this form handler or form display |
setcookie("ccname",$cname); | Set a cookie named “ccname” to be the value of $cname, which is one of the form inputs |
setcookie("ctype",$type); | Set a cookie named “ctype” to be the value of $type, which is one of the form inputs |
?> | Close PHP |
<html><head><title>Use cookie </title></head> | Normal HTML |
<body> | HTML |
<h1> Welcome | HTML |
<? | Restart PHP |
print ("$cname! </h1>\n"); | Display response |
print ("<br>You like $type cookies."); | Display response |
?> | Close PHP |
</body> | Body close tag |
</html> | HTML close tag |
<? } | Restart PHP. Closing bracket for the if true clause on if submitted |
else { ?> | Else clause. End PHP |
<html><head><title>Form for cookies </title></head><body> | HTML |
<form action="cookies.php" method=post> | Form tag |
Your name <input type=text name='cname' | Input tag |
value='<?print (@$ccname); ?>'> | Use $ccname for value of value attribute. Will use cookie if it exists. The @ prevents an error warning message |
<br> | Line break |
Your favorite cookie <input type=text name='type' | Input tag |
value='<? print (@$ctype); ?>'> | Use $ctype for value of value attribute. Will use cookie if it exists. The @ prevents an error warning message |
<br> | Line break |
<input type=hidden name='submitted' value=TRUE> | Input tag for hidden submitted variable |
<input type=submit value='send info'><input type=reset value='reset'> | Button labeled send info |
</form> | Close form |
</body> | Close body |
</html> | Close HTML |
<? } | End PHP. Closing bracket for the else clause |
?> | Close PHP |
To set a cookie with an explicit expiration time, ASP uses a property of the values in the Cookies collection; namely, the expires property. The first step is to determine the time. This is done using the JavaScript function for Date, which returns date and time. The next step for this example is to modify this value by FIVE minutes. This is done using methods of JavaScript date objects: getMinutes and setMinutes. The setMinutes method will do the right thing if the new value of minutes also changes the hours and day. Lastly, the calculated expiration must be converted to be the datatype expected by ASP. The expires property must be set with a time value in what ASP calls the Variant datatype. Most of the time, datatypes seem to take care of themselves, but this is one of the times when coding is necessary to change the datatype explicitly. The conversion (also called cast) from the JavaScript date datatype to Variant is done by the getVarDate method.
Here is the code for setting the cookies with an expiration time of five minutes from now:
var later=new Date(); later.setMinutes(later.getMinutes()+5 ); Response.Cookies("ccname") = sname; Response.Cookies("ccname").expires = later.getVarDate(); Response.Cookies("ctype") = stype; Response.Cookies("ctype").expires = later.getVarDate();
The PHP command to set a cookie to have an explicit expiration is the same command but with an additional parameter. The time() function returns a value of the current time. You need to add what you want to this value. For this example, it is written 5 times 60 just to make the five minutes clear. The PHP system does the correct thing with addition. The call to setcookie is:
setcookie("ccname",$cname,time()+5*60); setcookie("ctype",$type, time()+5*60);
The setting of a cookie is done in the HTTP header. This means it must be done before anything is sent to the client. The following script would cause an error because the html tags at the start cause a header to be generated:
<html><head><title>Form for cookies </title></head> <body> <?php if (@($submitted)) { setcookie("ccname",$cname); setcookie("ctype",$type); ?> <html><head><title>Use cookie </title></head> <body> <h1> Welcome <? print ("$cname! </h1>\n"); print ("<br>You like $type cookies."); ?> </body> </html> <? } else { ?> <form action="cookies.php" method=post> Your name <input type=text name='cname' value='<?print (@$ccname); ?>'> <br> Your favorite cookie <input type=text name='type' value='<? print (@$ctype); ?>'> <br> <input type=hidden name='submitted' value=TRUE> <input type=submit value='send info'> <input type=reset value='reset'> </form> </body> </html> <? } ?>
The PHP system would display the screen shown in Figure 13.9.
Figure 13.9: Screen shot showing warning messages.
Once you have these scripts working, you should repeat the steps outlined previously to examine the cookies. The screen shot in Figure 13.5 shows the cookie ctype stored by Netscape 7.
Netscape 6.2 stores its cookies in a file called cookies.txt. There would be entries such as:
sharon.ns.purchase.edu FALSE / FALSE 1036259442 ctype
chocolate+chip sharon.ns.purchase.edu FALSE / FALSE 1036259442 ccname
Jeanine
after running either of the cookies5min.asp or cookies5min.php.
In the case of Internet Explorer 6, the cookie file would be:
ctype chocolate+chip sharon.ns.purchase.edu/ 1536 1142620928 29526132 2953848224 29526131 * ccname Jeanine sharon.ns.purchase.edu/ 1536 1142620928 29526132 2953848224 29526131 *
The values other than the cookie name, value, server, and time (the 1142620928) are used in some way by Internet Explorer and not necessary to decipher.
The following examples show the use of session data. This time, the saved data includes a color for setting the background color (bgcolor) of the Web pages and displaying the time the session began. All of this also could have been done using cookies.
The example uses two scripts for two Web pages. The first presents and handles a form as shown in Figure 13.10.
Figure 13.10: Form for obtaining information.
After filling in the form, the screen would look like Figure 13.11.
Figure 13.11: Filled-in form.
After clicking the send info button, you would see the screen shown in Figure 13.12.
Figure 13.12: Screen showing response.
Notice the form data in the query string shown in the Address field. It contains the form data. The Next page hyperlink is provided to go to the second page. This Web page will make use of the session information. It is shown in Figure 13.13.
Figure 13.13: Shot of follow-up screen.
Notice the query string in the Address field this time: it contains a rather complex string of letters and numbers that is the session ID. Notice also the color (shade in this black-and-white book) of the page.
The PHP script for the first page ( session1.php) is shown in Table 13.3.
<?php | Start PHP |
if (@($submitted)) { | If test for handler or form |
session_start(); | Start the session |
session_register('cname'); | Register the variable named cname as a session variable |
session_register('type'); | Register type |
Session_register('bcolor'); | Register bcolor |
$starttime = time(); | Determine the current time |
session_register('starttime'); | Register starttime as a session variable |
?> | Close PHP |
<html><head><title>Use session values </title></head> | Normal HTML |
<body> | Normal body |
<h1> Welcome | Heading |
<? | Re-start PHP |
print ("$cname! </h1>\n"); | Display form input |
print ("<br>You like $type cookies."); | Display form input |
?> | End PHP |
<a href="session2.php">Next page </a> | Hyperlink to next page |
</body> | Body close |
</html> | HTML close |
<? } | Restart PHP. Close If submitted clause |
else { ?> | Else clause. End PHP |
<html><head><title>Form for session data </title></head><body> | HTML opening tags |
<form action="session1.php"> | Form tags |
Your name <input type=text name='cname'> | Input tag |
<br> | Line break |
Your favorite cookie <input type=text name='type'> | Input tag |
Your preferred background color <input type=text name='bcolor'> | Input tag |
<br> | Line break |
<input type=hidden name='submitted' value=TRUE> | Input tag for submitted |
<input type=submit value='send info'><input type=reset value='reset'> | Input tag for Submit button |
</form> | End form |
</body> | End body |
</html> | End html |
<? } ?> | Restart PHP to close off else clause and then end PHP |
The session2.php script is shown in Table 13.4. Note that the session_start function actually re-establishes the session. Any session variables are reinstated with the values set in previous Web pages.
<? session_start();?> | PHP: re-establish session. End PHP |
<html><head><title>Follow on page using session data </title></head> | Normal HTML |
<body bgcolor="<?print($bcolor);?>"> | Normal HTML. Use session variable to set bgcolor of page |
<h1> Welcome to the second page </h1> | Heading |
<? | Restart PHP |
print ("$cname! </h1>\n"); | Display session variable |
print ("<br>You like $type cookies."); | Display session variable |
print("<br>You began your visit at $starttime"); | Display session variable |
?><br> | End PHP. Line break |
<a href="session3.php">non-existent page </a> | One more link: this is to demonstrate that you could go to yet another page |
</body></html> | Ending HTML tags |
The time as displayed in the previous scripts is not too meaningful. An improvement would be the following:
$darray = getdate($starttime); $dhrs = $darray{"hours"}; $dmins = $darray{"minutes"}; if (strlen($dmins)<2) {$dmins = "0".$dmins;} print("<br>You began your visit at $dhrs:$dmins");
The if statement is necessary to prevent 2 hours and 5 minutes from appearing as 2:5 when you want 2:05.
The ASP session scripts follow the same format as the PHP scripts. This is one case in which the ASP code is simpler because there is no analog to PHP’s session_start. Since the start time is used here just for display, the code shows the use of the JavaScript date object method toString.
The first ASP script is shown in Table 13.5.
<%@ Language="JavaScript" %> | Set language as JavaScript |
<% | Start ASP |
var submitted=String(Request("submitted")); | Extract form data |
if (submitted != "undefined") { | If test for handler versus form |
cname=String(Request("cname")); | Set cname variable from form data |
ctype = String(Request("type")); | Set ctype variable from form data |
bcolor =String(Request("bcolor")); | Set bcolor data from form data |
var starttime = new Date(); | Determine current time |
Session("cname")=cname; | Set session value for “cname” to be value of cname variable |
Session("ctype")=ctype; | Same for ctype |
Session("bcolor")=bcolor; | Same for bcolor |
Session("starttime")= starttime.toString(); %> | Set session value for “starttime” to be starttime converted to a string End ASP |
<html><head><title>Set session values </title></head> | Normal HTML tags |
<body> | Body tag |
<h1> Welcome | Heading |
<% | Restart ASP |
Response.Write(cname+"! </h1>\n"); | Write out cname |
Response.Write("<br>You like "+ ctype+" cookies."); | Write out ctype |
%> | End ASP |
<a href="session2.asp">Next page </a> | Hyperlink to next page |
</body> | Body close |
</html> | HTML close |
<% } | Restart ASP to close If clause |
else { %> | Else clause. End ASP |
<html><head><title>Form for session data </title></head><body> | Normal HTML |
<form action="session1.asp" method="get"> | Form tag |
Your name <input type=text name='cname' > | Input tag |
<br> | Line break |
Your favorite cookie <input type=text name='type' ><br> | Input tag |
Your preferred background color <input type=text name='bcolor'> | Input tag |
<br> | Line break |
<input type='hidden' name='submitted' value=TRUE> | Input tag for hidden variable submitted |
<input type='submit' value='send'> | Button |
</form> | End form |
</body> | End body |
</html> | End HTML |
<% } %> | Re-open ASP to close Else clause. Close ASP |
The session2.asp script that is the next page that makes use of the session information is shown in Table 13.6.
<%@ Language="JavaScript" %> | Set JavaScript as language |
<% | Start ASP |
var bcolor = Session("bcolor"); | Extract bcolor from session |
var cname = Session("cname"); | Extract cname |
var ctype = Session("ctype"); | Extract ctype |
var starttime=Session("starttime"); | Extract starttime |
%> | End ASP |
<html><head><title>Follow on page using session data </title></head> | Normal HTML |
<body bgcolor="<%Response.Write (bcolor);%>"> | Body tag: break into ASP to get value of bcolor. End ASP |
<h1> Welcome to the second page </h1> | Heading |
<% | Start ASP |
Response.Write(cname+"! </h1>\n"); | Write out cname |
Response.Write("<br>You like "+ ctype+" cookies."); | Write out ctype |
Response.Write("<br>You began your visit at " + starttime); | Write out time |
%><br> | End ASP. Line break |
<a href="session3.asp">non-existent page </a> | Hyperlink to show you can go to another page |
</body></html> | Closing HTML tags |