FIT3084: Cookies in Perl CGI & PHP Scripts
In the previous lecture:
In this lecture:
References:
Sessions
A session is the time span over which a browser interacts with a server.
HTTP is stateless yet it is helpful if a server can keep track of the information it has exchanged with a client over a session, or across multiple sessions.
Storing information about a user raises privacy concerns.
What are cookies?
A cookie is an object storing information. Cookies have a name, value and expiry date / life time. Cookies are stored on the client / browser side. Cookies are created on the server by software such as a CGI program or PHP script. Cookies are sent back to the server each time a client request is made, allowing the server to know something about the client's previous interactions with it. This way, multiple interactions can be neatly bundled into a "session" of interaction since the server can keep track of a single user's interactions over time. |
Cookie Applications.
|
How are cookies exchanged?
Baking cookies with Perl CGI.
CGI.pm supports cookies.
To create a cookie*:
$myCookie = cookie( -name => myCookieName, -value => myCookieValue, -expires => myCookieExpiry ); |
* Other cookie attributes are also possible. Consult cpan.org for further information.
Sending cookies to the client with Perl CGI.
When creating a header using the CGI.pm you must include any cookies to send to the client:
header ( -cookie => $myCookie ); |
or | print $q->header( -cookie => $myCookie ); |
To send multiple cookies, call header() with an array reference:
$cookie1 = $q->cookie(-name=>'riddleName', -value=>"The Paradox"); $cookie2 = $q->cookie(-name=>'answers', -value=>\%answers); print $query->header(-cookie=>[$cookie1, $cookie2]); |
Retrieving cookies from the client with Perl CGI.
When a client requests the execution of a CGI script, it will pass any cookies that are associated with the script's web server, to the server in the header of its request.
Within the CGI script these can be accessed by name and assigned to a scalar variable (if they were created that way) or a %hash (for cookies created from a hash).
$riddle = $query->cookie('riddleName'); |
or | %answers = $query->cookie(-name=>'answers'); |
If the script is expecting multiple cookies, you can get a list of the names of all of the cookies by calling cookie() with no parameters:
@cookies = $query->cookie( ); |
or | foreach $name ($query->cookie( )) |
An example cookie Perl CGI script.
#!/usr/bin/perl
# a CGI perl program to demonstrate the use of cookies
use CGI; $q = new CGI;
# If there is already a last_time cookie sent from client to the
# server with the call to this script, collect it --- place its values in an @array.
@last_day = $q->cookie('last_time');
# Get the current date details using localtime.
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime;
# Convert the weekday number into a string day name.
# Perl's qw() - saves you from having to quote and comma-separate each element of a list by hand,
# simplifying the creation of an array with multiple elements.
$day_of_week_name = (qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)) [$wday];
# Convert the month number into a string month name abbreviation.
$month_name = (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)) [$mon];
# Store the date details in an array.
@dayDetails = ($day_of_week_name, $mday, $month_name);
# Create the new cookie from the date info. we have obtained.
$dayCookie = $q->cookie(-name => 'last_time', -value => \@dayDetails, -expires => '+2d');
# Put the cookie into the new header that will be returned by this CGI script.
print $q->header(-cookie=>$dayCookie);
print $q->start_html('This is dayCookie.pl');
# If this script was called without a pre-existing last_day cookie then # it must be the first time this CGI script was called from here. # scalar( ) converts an array to a scalar value --- the array length. if (scalar(@last_day) == 0) { print "This must be your first visit to this site! <br />"; } # Otherwise, if this CGI script was just called with a pre-existing cookie, then
# print out what the cookie holds... the date of last access by extracting the elements
# of the array we assigned it to above!
else
{
($day_of_week_name, $day_of_month, $month_name) = @last_day;
print "Your last visit was on $day_of_week_name $month_name $day_of_month.";
}
print $q->end_html; |
Run the Perl cookie script.
Creating PHP Cookies
setcookie( "myCookieName", "myCookieValue", myCookieExpiry ); |
Example cookie:
setcookie( "completedPeerAssessment", "true", time() + (86400*7) ); |
The example above sets a cookie called completedPeerAssessment to the value true with expiry date of the present time() plus 7 days (86400 seconds in 1 day).
Reading PHP Cookies
if (IsSet($_COOKIE [ "completedPeerAssessment" ]) { $cookieValue = $_COOKIE [ "completedPeerAssessment" ]; print "Peer assessment cookie value is $cookieValue"; } |
PHP reads cookies much like it reads form submissions, from a hash... pretty simple huh?!
An Example PHP Cookie Script and Form Processor.
This XHTML form is specified here with the tag: <form action="cgi-bin/lectPHPCookieScript.cgi" method="post" name="cookieScript" id="cookieScript"> Here is lectPHPCookieScript.cgi <?php # Also make a cookie called "visits" and set its value to 1
setcookie("visits", 1);
# print a welcome message to the person named in the POST parameter
$message = "Welcome $_POST[name] to this site for your first visit!";
}
# otherwise, the cookie called "nameCookie" has already been made else { # increment the counter in the visits cookie setcookie("visits", ++$_COOKIE["visits"]); # print out a welcome message to the person named in the original "nameCookie"
$message = "Welcome back $_COOKIE[nameCookie]. <br />" .
"You must like us to have visited $_COOKIE[visits] times!";
}
?>
<html><head><title>PHP Visit Counter</title></head>
<body><p>
<?php
print "$message";
?>
</p></body></html> |
In your own time: | Run the PHP cookie script above twice, the first time with your name in the form box, and the second time with somebody else's name. What does the script do? Why? Extend the cookie scripts above to accept some information from the user and store it in the cookie. Using PHP, duplicate the effect of the Perl CGI cookie script above. |
Important notes about cookies:
|
©Copyright Alan Dorin 2009