Download CGI.pm

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

URL redirection wikipedia , lookup

Transcript
Chapter 9: Perl and CGI Programming
CGI Programming
Acknowledgement: Some materials are taken from Teach Yourself CGI Programming with PERL 5 in a Week
Creating an Interactive Web Page
After studying this lesson, you
should be able to:
• Use Perl and CGI scripts to make
your web pages interactive
Setting Up a Web Page
• You can create a Web page using HTML (Hyper
Text Markup Language)
• HTML is a format for creating documents with
embedded codes known as tags
• The tags tell the Web browser how to display the
page
• After you use HTML to create a Web page, you
then publish the page on a Web server
Creating Web Pages
• You may use a visual HTML editor, such as
Netscape Composer or Microsoft FrontPage, to
create Web pages
• If you have no visual HTML editor, all you need is
a text editor
• All special codes contained inside angled
brackets <> are tags
• You can use tags to set background and
foreground colors and to manipulate text with
such tags as <FONT SIZE=n> (insert text here)
HTML Example
• mypage.html
<html>
<head>
<title>Title of page</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>
HTML Form
• Please see handout for detailed
examples
• http://cse.unl.edu/~yzhu/cs251/cgi/form_demo.html
CGI Overview
• Perl is the most commonly used language for CGI
(Common Gateway Interface) programming
• CGI is a protocol, or set of rules, governing how
browsers and servers communicate
• CGI lets Web browsers pass information to
programs written in any language
• If you want to create a lightning-fast search
engine, then your CGI program will most likely be
written in C or C++. However, most other
applications can use Perl.
Hello World
• hello1.cgi
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "Hello, world!\n";
• chmod u+x hello1.cgi
• http://cse.unl.edu/~yourname/hello1.cgi
• Note there is a newline between the
content-type and the header or body
Hello World
• hello2.cgi
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<html><head><title>Hello World</title></head>\n";
print "<body>\n";
print "<h2>Hello, world!</h2>\n";
print "</body></html>\n";
• Headings are defined with the <h1> to <h6> tags. <h1>
defines the largest heading. <h6> defines the smallest
heading.
Hello World
• hello3.cgi
#!/usr/bin/perl
print "Content-type: text/html\n\n";
$MyDate = `date`;
chop $MyDate;
print <<"ending_print_tag";
<html>
<head><title>Hello World</title></head>;
<body>
<h1>Hello, world!</h1>
<h2>Today is $MyDate</h2>
</body>
</html>
ending_print_tag
Mysteries of Quotation Marks
• The paired backquotes (``) tell Perl to perform
the system action inside the quotation marks.
• The paired double quotation marks ("") tell
Perl to look for special characters and interpret
them inside the print string.
• The paired single quotation marks ('') tell Perl
to not look for or process any special characters
in the print string.
Hello World: Using CGI.pm Module
• CGI.pm module is part of the standard library, and
has been since Perl version 5.004.
• hello4.cgi
#!/usr/bin/perl
use CGI;
#
$cgi = CGI->new;
# ($cgi is now the object)
print $cgi->header;
# function call: $obj->function
print $cgi->start_html("Hello World");
print $cgi->h2("Hello, world!"),
'This is cool';
print $cgi->end_html;
Interactive Webpages
• The HTML Form tag is the basis for passing data to your
CGI programs on the server.
• CGI program and the HTML form work together to build
interactive web pages, to allow your HTML document to
accept input, to build dynamic web pages.
• http://www.somedomain.com/cgibin/somescript.cgi?name=BillGates&position=monopolist
• The question mark (?) signifies the beginning of what's
called a query string (in your Perl program, you could
access this through $ENV{'QUERY_STRING'})
• The "name=BillGates" and "position=monopolist" are
referred to as name/value pairs and they are separated by
ampersands (&).
HTML Form
• HTML Form tag has the following syntax:
<FORM METHOD="GET or POST" ACTION="URI"
EncTYPE=application/x-www-form-urlencoded>
• ACTION: The URI (which usually will be a CGI script) to which
the form's data is passed. The data submitted to the CGI script
(URI) is based on the EncTYPE and the Method attributes.
• EncTYPE: Defines the MIME content type used to encode the
form's data. The only valid type now is the default value
"application/x-www-form-urlencoded". Because the default
value is the only valid value at the moment, you do not need to
include this attribute in your Form tag.
• METHOD: Defines the protocol used to send the data entered in
the form's fields. The two valid method protocols are Post and
Get.
– Get is the default method, but Post has become the preferred method for
sending form data.
– The Get method's data is shipped appended to the end of the request URI,
and it is encoded into the environment variable QUERY_STRING.
– The Post's data is appended after the response headers as part of standard
input.
HTML Form: Get & Post
Syntax:
<FORM METHOD=get ACTION="A CGI PROGRAM">
<FORM METHOD=post ACTION="A CGI PROGRAM">
• Get: The Get method sends your URI-encoded data
appended to the URI string. The URI- encoded data and any
path information are placed in the environment variables
QUERY_STRING and PATH_INFO.
• Post: The Post method also use URI to encode your data. It
sends your data after all the request headers have been sent
to the server, however. It includes the request header
content length so that your CGI program can figure out how
much data to read.
• "GET" is basically for just getting (retrieving) data whereas
"POST" may involve anything, like storing or updating data,
or ordering a product, or sending E-mail.
Get example
• get_demo.html
<HTML>
<BODY>
<FORM METHOD="get" ACTION=“get_demo.cgi">
<INPUT TYPE="text" NAME="in" SIZE="20"
MAXLENGTH="40" VALUE="hello there">
<INPUT TYPE="submit" NAME="button" VALUE="Send">
</FORM>
</BODY>
</HTML>
• http://cse.unl.edu/cgi-bin/script.pl?in=hello+there&button=Send
• Everything after the ? is the "URL Encoded" contents of the form,
the "QUERY_STRING".
– QUERY_STRING = “in=hello+there&button=Send”
How to Read Data from Get method?
•
Here are the steps that a Perl program will take to translate the form data
from a GET method back into useful strings:
1. Split $ENV{'QUERY_STRING'} into separate keywords on "&"
2. Each key-value will be split on "="
3. Each key and value will be unencoded: each "+" will be changed to a space
and %xx codes will be translated back to characters.
• A simplified demo code:
#! /usr/bin/perl
print "Content-type: text/plain\n\nHere's the form data:\n\n";
# separate each keyword
foreach ( split( /&/, $ENV{'QUERY_STRING'} ) ) {
( $key, $val ) = split( /=/, $_, 2 ); # separate the key and value
$key=~s/\+/ /g; # translate + to spaces
$val=~s/\+/ /g; # translate + to spaces
$key=~s/%([0-9a-f]{2})/pack("c", hex($1))/gie; # translate %xx codes to characters
$val=~s/%([0-9a-f]{2})/pack("c", hex($1))/gie; # translate %xx codes to characters
print "$key = $val\n";
}
Post Example
• post_demo.html
<HTML>
<BODY>
<FORM METHOD="post" ACTION=“post_demo.cgi">
<INPUT TYPE="text" NAME="in" SIZE="20"
MAXLENGTH="40" VALUE="hello there">
<INPUT TYPE="submit" NAME="button" VALUE="Send">
</FORM>
</BODY>
</HTML>
•
Now, when the form data is sent by the web browser, the URL will be
unchanged. Instead, the HTTP request received by the web browser from
the POST method will look like this:
POST /cgi-bin/script.pl HTTP/1.0
Content-type: application/x-www-form-urlencoded
Content-length: 26
in=hello+there&button=Send
How to Read Data from Post method?
•
We won't use the QUERY_STRING environment variable. Instead, the
CONTENT_LENGTH variable will tell us the length of the URL-encoded
string containing the form data. Here are the steps:
1. Read $ENV{'CONTENT_LENGTH'} bytes from STDIN (standard input) into a
temporary variable called $temp
2. Split $temp into separate keywords on "&"
3. Each key-value will be split on "="
4. Each key and value will be unencoded: each "+" will be changed to a space
and %xx codes will be translated back to characters.
•
A simplified code
#! /usr/local/bin/perl
print "Content-type: text/plain\n\nHere's the form data:\n\n";
read STDIN, $temp, $ENV{'CONTENT_LENGTH'}; # read POST data from STDIN
foreach ( split( /&/, $temp ) ) {# separate each keyword
( $key, $val ) = split( /=/, $_, 2 ); # separate the key and value
$key=~s/\+/ /g; # translate + to spaces
$val=~s/\+/ /g; # translate + to spaces
$key=~s/%([0-9a-f]{2})/pack("c",hex($1))/gie;
$val=~s/%([0-9a-f]{2})/pack("c",hex($1))/gie;
print "$key = $val\n";
}
Read from Get and Post
#! /usr/local/bin/perl
print "Content-type: text/plain\n\nHere's the form data:\n\n";
if ($ENV{'CONTENT_LENGTH'} > 0) {
read STDIN, $temp, $ENV{'CONTENT_LENGTH'}; # read POST data from STDIN
$temp.="&".$ENV{'QUERY_STRING'} if length $ENV{'QUERY_STRING'}; # add in the
GET data:
} else {
$temp=$ENV{'QUERY_STRING'}; # read only the GET data
}
foreach ( split( /&/, $temp ) ) {# separate each keyword
( $key, $val ) = split( /=/, $_, 2 ); # separate the keys and values
$key=~s/\+/ /g; # translate + to spaces
$val=~s/\+/ /g; # translate + to spaces
$key=~s/%([0-9a-f]{2})/pack("c",hex($1))/gie; # translate %xx codes to characters
$val=~s/%([0-9a-f]{2})/pack("c",hex($1))/gie; # translate %xx codes to characters
print "$key = $val\n";
}
CGI Using Standard Library
• cgi-lib.pl: A nice, compact library for
performing simple CGI operations.
• CGI.pm: A robust Perl 5 library for
reading CGI data, saving the state of
your program, generating HTML Web
fill-out forms, and generating other basic
HTML tags.
cgi-lib.pl
• cgi-lib.pl was written by Steven E.
Brenner
• The cgi-lib.pl library makes CGI
scripting in Perl easy enough for
anyone to process forms and create
dynamic Web content
Demo for cgi-lib.pl
CGI.pm
• This perl 5 library uses objects to create
Web fill-out forms on the fly and to parse
their contents.
• Everything is done through a “CGI”
object.
• It offers a rich set of functions for creating
fill-out forms. Furthermore, instead of
remembering the syntax for HTML form
elements, you just make a series of Perl
function calls.
CGI.pm
#!/usr/bin/perl
use CGI;
$query = new CGI;
print $query->header;
print $query->startform;
print "What's your name? ",$query->textfield('name');
print "<P>What's the combination? ",
$query->checkbox_group('words',['eenie','meenie','minie','moe']);
print "<P>What's your favorite color? ",
$query->popup_menu('color',['red','green','blue','chartreuse']);
print "<P>",$query->submit;
print $query->endform;
print "<HR>\n";
if ($query->param) {
print "Your name is <EM>",$query->param('name'),"</EM>\n";
print "<P>The keywords are: <EM>",join(", ",$query->param('words')),
"</EM>\n";
print "<P>Your favorite color is <EM>",$query->param('color'),"</EM>\n";
}
Summary
• CGI (Common Gateway Interface) allows
you to build dynamic and interactive web
pages.
• Use CGI modules to simplify your design
– cgi-lib.pl
– cgi.pm