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?

cookie monster

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.


amazon personalised

Cookie Applications.

  • The server keeps track of personal info. :

    • preferences for books or music
    • interests in subjects of news articles
    • which web pages have been read (or which have not)
    • items added to a shopping cart

  • In general, the aim is that cookies allow a website to be customised for an individual user.

How are cookies exchanged?

cookie viewer

Every request from a client to a server can include cookies in the header.

  • If a request is made by a client to a server, all cookies associated with that server are sent along with the request.

Every response from a server to a client can include cookies in the header.

  • If a browser has cookies enabled, a cookie from a particular web server is stored on the client machine.
  • Users can see what cookies are on their machine and what these contain by using their browser's cookie viewer (e.g. at left).

When a cookie's expiry date is reached, it is deleted from the client.


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( ))
{
print $query->cookie($name); }

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.

Cookie Form

Name


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
# if there is not yet a cookie called "nameCookie"... if (!isset($_COOKIE["nameCookie"])) { # ...make one, and set its text content to the person's name that was # sent from the fill-out form as a POST parameter to this script setcookie("nameCookie", $_POST["name"]);
    # 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.
Install the new scripts to run on a web page from your own account.

Using PHP, duplicate the effect of the Perl CGI cookie script above.

 

Important notes about cookies:

  • Cookies are sent with the document header back to the client requesting a document.
  • Hence, any cookies must be created before a PHP script generates any XHTML output (including <html> and <head> tags) or it will not be successful.

  • Never use cookies to store sensitive information such as credit card numbers. They are not secure.

  • Users can set their web browser preferences to reject cookies.
  • They are not a guaranteed means of storing information!
cookies off!



This lecture's key point(s):


Courseware | Lecture notes

©Copyright Alan Dorin 2009