Perl Chapter 9
description
Transcript of Perl Chapter 9
Perl Chapter 9
CGI Programming with Perl
• Assume familiar with Web and HTML– Hypertext Markup Language: describes layout of
documents– Web browsers (clients)– Web servers: run on computer connected to
Internet; provides documents to browsers– Documents accessed by URL– Need computation? Write programs in a
programming language like Java, php, Perl
Common Gateway Interface (CGI)
• provides a standard way a browser can call, pass data to and receive response from programs on server
• CGI: interface between server program and other software
• HTML results from program returned to server using CGI
• Way to dynamically create web pages
Necessary tasks
• decode text values (text manip)• CGI program needs access to ENV (servers use
ENV variables to pass info to CGI)• access to other software and utilities (Unix shell
command)
• Perl fulfills these requirements• Usually Perl CGI programs in specific place on
server - folder called cgi-bin
Simple Linkage to CGI Programs
• Simple – no data from web page; produces only text string as output
• <A HREF = http://cs.mwsu.edu/~stringfe/cgi-bin/hello.pl> call hello </A>
• call hello is the link, the path is where the CGI program hello.pl is at
• CGI program hello.pl must create HTML version of communication
• Connection to client is through STDOUT server client … SO USE print
• First line of HTML output must specify content type of output (most text/html).
print “Content-type:text/html\n\n”;
– must be a blank line!!!
Demos
• show hello.htm; view source• show hello.pl– NOTE: #!/usr/bin/perl
• show SSH client• show SSH FTP
• show simple Unix commands
Handling Forms
• Way to get information from browser• Need forms: collection of widgets to solicit
responses• MUST INCLUDE a submit button• When clicked, it sends a string representation
of values of widgets to server
• string widget_name=widget_value pairs
• 2 means of communicating values in form to CGI program
– Get (default)• data string sent through environment variables
– Post• sent through standard input so CGI program can read it• use tag METHOD=“POST”
• To create HTML form, need a <FORM> tag– attribute is ACTION: specifies URL of CGI program
that process values of widget
<FORM ACTION=http://.../prog.pl METHOD=“POST”>
Kinds of widgets
• all begin with <INPUT> tag TYPE is an attribute
• text widget• <INPUT TYPE=“text” NAME=“name” SIZE=30>– user can type text, default size is 20
• multiline, use <TEXTAREA> tag … will give you a scroll bar
• checkbox widget – toggle switch<INPUT TYPE=“checkbox” NAME=“AutoRemember”>
– www.amazon.com checkbox gift card
• radio widget – collection of closely related buttons– buttons have same name, but different values<INPUT TYPE=“radio” NAME=“payment” VALUE=“visa” CHECKED> Visa <BR>
<INPUT TYPE=“radio” NAME=“payment” VALUE=“mc” CHECKED> Mastercard <BR>
• menu widget – scrolled list– <SELECT> caluse– SIZE attribute number of items visible– <OPTION> tag – specifies items of a menu
<SELECT name=state id=“sel_state” SIZE=1 class=content-sm>
<option value=“”>All other destinations </option>
<option value=“TN-Tennessee”>TN</option>
– http://travelocity.com/Hotels
• widgets often aligned by placing in tables.– <TABLE> <TR> <TH> and <TD> tags.
• View sources of web pages to learn more
• form must have submit button and a reset button– two buttons with type “submit” and “reset”– values are labels (text showing on button)
• submit cause 2 actions– value of form sent to server– CGI program executed
• reset erases values of all widgets
Examples
• web pages – view source– round.htm– nutsales.htm– survey.htm
Value string of form
• value string of form has names and values of all widgets
• names and values separated by = • adjacent pairs separated by &• special chars coded %HH (2 hex digis)– space is %20 in hex, tilda is %7E
• query string of form is transmitted to CGI program by either GET or POST
• radio button collection called fruit
name=Max%20Marks&fruit=apples%21
Get
• query string attached to URL (of CGI program) with ? between URL?query_string – attached at submit
• server removes query string and assigns it to env’t variable QUERY_STRING, accessible to CGI program
• Disadv: some browsers/servers imose limit on length of URL and truncate
Post
• query string is read by CGI program as STDIN• length of query string is available in
CONTENTLENGTH environment variable• Advantage: No length limit• (Doesn’t seem to work with CGI.pm)
Converting form input to useful format
1. put query string in $string_var– 2 ways determined by Get or Post
2. split $string_var on & to set array of strings
@name_value_pairs=split(/&/, $query_string);
3. split each element of array on =
($name, $value)=split(/=/, $name_value);
1. plus signs in values translated to blanks with tr operator $value =~ tr /+/ /;
2. convert coded special char into ordinary chars using substitute op s
$value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack(“C”, hex($1))/eg;
• find pattern starting with % followed by 2 hex digits• [ ] indicates optional• ( ) saved in $1 by matching op• hex function - $1 as parameter, does replacement part• pack into a byte using “C” as first parameter• use global option – more than one occurrence
• See nuts.pl• nutsales2.htm
Basics of CGI.pm
• many repeatable parts in a CGI program• CGI.pm is a Perl module containing functions
to do common things• gives you short cuts• available by including use statement• import parts by categories or collection• most useful in general are standard and html3
use CGI qw(:standard :html);
Some common thingsprint header( );
print start_html(‘Sebesta’s Home Page’);
print end_html();
same as
print “Content-type: text/html\n\n”;
print “<HEAD> \n”;
print “<TITLE> Sebesta’s Home Page </TITLE> \n”;
print “</HEAD> \n”;
print “<BODY> \n”;
print “</BODY> </HTML> \n”;
• getting parameter values can be done in single step using param function
my $name=param(“name”);
my ($name, $fruit)=(param(“name”), param(“fruit”));
• See nuts2.pl
Reading/Writing Files
• WHEN THEY COULD BE ACCESSED by 2 or MORE executions of CGI program
$lock=2;
$unlock=8;
open (INFILE, …)
flock (INFILE, $lock);
…
flock(INFILE, $unlock);
close(INFILE);
• can open file, read, close it, open file, write, close it, …– that’s okay if it is a small file
• can open file, read, close it, open file, write, close it, …– that’s okay if it is a small file
Tables• Can display perl program results in table• tedious to generate without CGI.pmprint table ({-border => undef}, #standard default border
caption(“Caption”),
Tr(
[th([“Col1”, “Col2”, “Col3”]),
th(“row1”).td ([“val1”,”val2”]),
…
th(“rown”).td ([“val1”,”val2”])
]
)
);
• Notes: tr is a pattern matching function• Using scalar strings
Using arrays for each row of data
• @row1, @row2, …@rown• use unshift to put titles of row categories into
first position of row arrays unshift(@row1, “row1”);
• make headings array @headings=(“ mon”, “tue”, …”sun”);
• put headings and rows into table@rows=th(\@headings);
push(@rows, td(\@row1), … td(\@rown));
• so rows contain addresses of arrays
print table ({-border=undef},caption(“Caption”),
Tr (\@rows)
);