Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
Perl, CGI, sessions - complete application template, full demo
State and Cookies example from a Well House Consultants training course
More on State and Cookies [link]

This example is described in the following article(s):
   • new 'Perl on the Web' example - [link]

If you're searching for a page where you can run this program, select here

This example references the following resources:
http://www.wellho.net/cgi-bin/demo/sweetest.pl
http://www.wellho.net/
http://www.wellho.net/course/pw.html

Source code: sweetest.pl Module: P407
#!/usr/bin/env perl

# This example online to try at
# http://www.wellho.net/cgi-bin/demo/sweetest.pl

=head1 Perl web application framework - sessions and hidden fields

=head2 Introduction to general code

This is a demonstration program showing which provides the shell
framework for a web based CGI application written in Perl.

This example if the third of three - known as "sweetest". The other
two examples, also downloadable from http://www.wellho.net, are
known as sweet and sweeter. You can learn / study sweet and
sweeter to help you understand the principles involved. We suggest
you work with sweetest if you're going to write an application
yourself that's based on the principles illustrated here.

=item 1. read any incoming form

=item 2. Use the value read to pick up the session

=item 3. Do any work to analyse inputs and validate them

=item 4. Do work to prepare for next page

=item 5. Save the session

=item 6. Send out the response page

=cut


# Date stamp for page
@now = (gmtime())[3,4,5];
$fill{"now"} = sprintf("%d/%d/%d",$now[0],$now[1]+1,$now[2]+1900);

$fill{"title"} = "Sample Perl/CGI session (shopping cart) demo";

$sessdir = "../../sessions";

print "Content-type: text/html\n\n";

# item 1. read any incoming form
#-------------------------------

collect_form();

# item 2. Use the value read to pick up the session
#--------------------------------------------------

if ($form{plsess}) {
        $sessname = $form{plsess};
        open (FHS,"$sessdir/$sessname.ses");
        while (<FHS>) {
                chop;
                ($name,$val) = split;
                $val =~ tr/+/ /;
                $val =~ s/%(..)/pack("C",hex($1))/eg;
                $session{$name} = $val;
        }
} else {
        $sessname = $$.time();
        # Take the opportunity of a new session to clean up stale ones
        opendir (DH,$sessdir);
        while ($fname = readdir DH) {
                next if ($fname =~ /^\./);
                if (-M "$sessdir/$fname" > 0.5) { # half a day
                        unlink "$sessdir/$fname";
                }
        }
}
$fill{plsess} = $sessname;
$stepnumber = $session{step};

# Inputs in %session and %form translate to %session and %fill

# item 3. Do any work to analyse inputs and validate them
#--------------------------------------------------------

$aok = 1;
$errstr = "";
if ($stepnumber == 0) { # Initialisation
        # Move on to next step - prepare for page 1
        $stepnumber = 1;
} elsif ($stepnumber == 1) {
        $aok *= checkinput("yourname","name",'\w',
                "Name must include a word character");
        $aok *= checkinput("youremail","email",'^\s*\S+@\S+\s*$',
                "email address of form xxx\@xxx.xxx required");
        $stepnumber++ if ($aok);
} elsif ($stepnumber == 2) {
        $aok *= checkinput("yourtown","town",'^\s*\w',
                "Town name must start with a letter");
        $aok *= checkinput("yourpostcode","postcode",
                "^\s*[A-Z]{1,2}[1-9]",
                "Must start with 1 or 2 capital letters followed by a digit");
        $stepnumber++ if ($aok);
} else {
}

# item 4. Do work to prepare for next page
#-----------------------------------------

$fill{status} = "You are at page $stepnumber of 3";
$fill{stuff} = "Results will appear here";
$fill{errstr} = $errstr;
$fill{form} = "<form method=POST><table border=1><input name=plsess type=hidden ".
                "value=".$fill{plsess}.">";

if ($stepnumber == 1) {
        $fill{"form"} .= formbox("Please enter your name","yourname");
        $fill{"form"} .= formbox("Please enter your email address","youremail");
} elsif ($stepnumber == 2) {
        $fill{"form"} .= formbox("Please tell us your town name","yourtown");
        $fill{"form"} .= formbox("Please enter your postcode","yourpostcode");
} elsif ($stepnumber == 3) {
        # This is where all the data entry has been completed and has been checked
        # to be valid and in a complete application we would add the code to conclude
        # the transaction. For the demonstration, we just echo the user's inputs and
        # then clear up the session behind ourself.
        $fill{stuff} = "<b>Hello ".webify($session{name})." from ".
                webify($session{town})."<br>";
        $fill{stuff} .= "email ".webify($session{email})." pc ".
                webify($session{postcode})."</b><br>";
        $stepnumber = 0;
        unlink "$sessdir/$sessname.ses";
        $completed = 1;
} else {
}

$fill{form} .= "<tr><td>&nbsp;</td><td><input type=submit></td></tr></table></form>";
$fill{form} = "<a href=\"\">Restart Demonstration</a>" if ($completed); # No next form if application completed

# item 5. Save the session
#-------------------------

# If the user's session has been completed, don't save the "in progress" file"

if (! $completed) {
        $session{step} = $stepnumber;
        open (FHS,">$sessdir/$sessname.ses");
        foreach $name (keys %session) {
                $val = $session{$name};
                $val =~ s/%/%25/g;
                $val =~ s/\+/%2b/g;
                $val =~ s/\n/%0a/g;
                print FHS "$name $val\n";
                }
        close FHS;
        }

# item 6. Send out the response page
#-----------------------------------
# Complete the output template and send it to the user

$fill{step} = $stepnumber;

while (<DATA>) {
        s/%(\w+)%/$fill{$1}/g;
        print;
        }

################## Standard functions

=head2 Standard functions

Note that the following standard functions would be placed into a
separate file (a module) for a live application. For the purpose of
this demo, we've put everyting into the one file

=cut


########################

# Code to "clean" up text strings for safe web display

sub webify {
        $_ = $_[0];
        s/&/&amp;/g;
        s/</&lt;/g;
        s/>/&gt;/g;
        s/"/&quot;/g;
        return $_;
        }

########################

# Code to translate form inputs (GET or POST) into a hash

sub collect_form {

if ($ENV{"REQUEST_METHOD"} eq "POST") {
        read(STDIN,$buffer,$ENV{"CONTENT_LENGTH"});
        $form{"method"} = "POST";
} else {
        $buffer = $ENV{QUERY_STRING};
        $form{"method"} = "GET";
}

@fof = split(/&/,$buffer);
foreach $field(@fof) {
        ($name,$value) = split(/=/,$field);
        $value =~ tr/+/ /;
        $value =~ s/%([a-fA-F0-9]{2})/pack("C",hex($1))/eg;
        if ($form{$name}) {
                $form{$name} .= "\n$value";
        } else {
                $form{$name} = $value;
                }
        }
}

########################

# Code to generate a table row that includes a prompt and an input box
# Adds error messages and old ("sticky") values in

sub formbox {
        my ($text,$fieldname) = @_;
        $add = "";
        if ($errtab{$fieldname}) {
                $add="<br><font color=red>$errtab{$fieldname}</font>";
                }
        $text = "<tr><td>".webify($text)."$add</td><td><input name=$fieldname ".
                "value=\"".webify($form{$fieldname})."\"></td></tr>";
        return $text;
        }

########################

# Validate a form input against a regular expression

sub checkinput {
        my ($fieldname,$sessname,$rematch,$errmsg) = @_;
        $good = 1;
        if ($form{$fieldname} !~ /$rematch/) {
                $good = 0;
                $errtab{$fieldname} = $errmsg;
                $errstr = "Please correct the errors noted and resubmit";
        } else {
                $session{$sessname} = $form{$fieldname};
        }
        return $good;
}
##################################################################

# After the __END__ we'll place the template for all response pages

__END__
<html><head>
<title>%title% - Well House Consultants demo</title>
</head>
<body bgcolor=#CCFFFF>
<h1>Demonstration - %title%</h1>
This is the introductory piece of text about this application.<hr>
This is the current status:<br><br>%status%<hr>
<font color=red>%errstr%</font>
%form%<hr>
Here are your results:<br><br>%stuff%<hr>
<i>This is a sample page generated by a training course example from
<a href=http://www.wellho.net/>Well House Consultants</a>. You can learn
how to write web based applications such as this on our
<a href=http://www.wellho.net/course/pw.html>Perl on the Web</a> course.</i><br><br>
Copyright Well House Consultants, %now% <br><br>
<h4>debug info: page no. %step%, session %plsess%</h4>
</body></html>

Learn about this subject
This module and example are covered on our public Using Perl on the Web course. If you have a group of three or more trainees who need to learn the subject, we can also arrange a private or on site course for you.

Books covering this topic
Yes. We have over 700 books in our library. Books covering Perl are listed here and when you've selected a relevant book we'll link you on to Amazon to order.

Other Examples
This example comes from our "State and Cookies" training module. You'll find a description of the topic and some other closely related examples on the "State and Cookies" module index page.

Full description of the source code
You can learn more about this example on the training courses listed on this page, on which you'll be given a full set of training notes.

Many other training modules are available for download (for limited use) from our download centre under an Open Training Notes License.

Other resources
• Our Solutions centre provides a number of longer technical articles.
• Our Opentalk forum archive provides a question and answer centre.
The Horse's mouth provides a daily tip or thought.
• Further resources are available via the resources centre.
• All of these resources can be searched through through our search engine
• And there's a global index here.

Web site author
This web site is written and maintained by Well House Consultants.

Purpose of this website
This is a sample program, class demonstration or answer from a training course. It's main purpose is to provide an after-course service to customers who have attended our public private or on site courses, but the examples are made generally available under conditions described below.

Conditions of use
Past attendees on our training courses are welcome to use individual examples in the course of their programming, but must check the examples they use to ensure that they are suitable for their job. Remember that some of our examples show you how not to do things - check in your notes. Well House Consultants take no responsibility for the suitability of these example programs to customer's needs.

This program is copyright Well House Consultants Ltd. You are forbidden from using it for running your own training courses without our prior written permission. See our page on courseware provision for more details.

Any of our images within this code may NOT be reused on a public URL without our prior permission. For Bona Fide personal use, we will often grant you permission provided that you provide a link back. Commercial use on a website will incur a license fee for each image used - details on request.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2024: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/resources/ex.php • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb