chapter 9: perl and cgi programming cgi programming acknowledgement: some materials are taken from...

Download Chapter 9: Perl and CGI Programming CGI Programming Acknowledgement: Some materials are taken from Teach Yourself CGI Programming with PERL 5 in a Week

Post on 03-Jan-2016

219 views

Category:

Documents

3 download

Embed Size (px)

TRANSCRIPT

  • Chapter 9: Perl and CGI Programming

    CGI ProgrammingAcknowledgement: Some materials are taken from Teach Yourself CGI Programming with PERL 5 in a Week

  • Creating an Interactive Web PageAfter studying this lesson, you should be able to:Use Perl and CGI scripts to make your web pages interactive

  • Setting Up a Web PageYou can create a Web page using HTML (Hyper Text Markup Language)HTML is a format for creating documents with embedded codes known as tagsThe 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 PagesYou may use a visual HTML editor, such as Netscape Composer or Microsoft FrontPage, to create Web pagesIf you have no visual HTML editor, all you need is a text editorAll special codes contained inside angled brackets are tagsYou can use tags to set background and foreground colors and to manipulate text with such tags as (insert text here)

  • HTML Examplemypage.html

    Title of page

    This is my first homepage. This text is bold

  • HTML FormPlease see handout for detailed examples

    http://cse.unl.edu/~yzhu/cs251/cgi/form_demo.html

  • CGI OverviewPerl is the most commonly used language for CGI (Common Gateway Interface) programmingCGI is a protocol, or set of rules, governing how browsers and servers communicateCGI lets Web browsers pass information to programs written in any languageIf 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 Worldhello1.cgi#!/usr/bin/perlprint "Content-type: text/html\n\n";print "Hello, world!\n";

    chmod u+x hello1.cgihttp://cse.unl.edu/~yourname/hello1.cgiNote there is a newline between the content-type and the header or body

  • Hello Worldhello2.cgi#!/usr/bin/perlprint "Content-type: text/html\n\n";print "Hello World\n";print "\n";print "Hello, world!\n";print "\n";

    Headings are defined with the to tags. defines the largest heading. defines the smallest heading.

  • Hello Worldhello3.cgi#!/usr/bin/perlprint "Content-type: text/html\n\n";$MyDate = `date`;chop $MyDate;print
  • Mysteries of Quotation MarksThe 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->functionprint $cgi->start_html("Hello World");print $cgi->h2("Hello, world!"),'This is cool';print $cgi->end_html;

  • Interactive WebpagesThe 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/cgi-bin/somescript.cgi?name=BillGates&position=monopolistThe 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 FormHTML Form tag has the following syntax:

    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 & PostSyntax:

    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 exampleget_demo.html

  • 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: Split $ENV{'QUERY_STRING'} into separate keywords on "&" Each key-value will be split on "=" 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/perlprint "Content-type: text/plain\n\nHere's the form data:\n\n";# separate each keywordforeach ( 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 Examplepost_demo.html

  • 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: Read $ENV{'CONTENT_LENGTH'} bytes from STDIN (standard input) into a temporary variable called $temp Split $temp into separate keywords on "&" Each key-value will be split on "=" 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/perlprint "Content-type: text/plain\n\nHere's the form data:\n\n";read STDIN, $temp, $ENV{'CONTENT_LENGTH'}; # read POST data from STDINforeach ( 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 Librarycgi-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.plcgi-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.pmThis 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/perluse CGI;$query = new CGI;print $query->header;print $query->startform;print "What's your name? ",$query->textfield('name');print "What's the combination? ", $query->checkbox_group('words',['eenie','meenie','minie','moe']);print "What's your favorite color? ", $query->popup_menu('color',['red','green','blue','chartreuse']);print "",$query->submit;print $query->endform;print "\n";if ($query->param) { print "Your name is ",$query->param('name'),"\n"; print "The keywords are: ",join(", ",$query->param('words')), "\n"; print "Your favorite color is ",$query->param('color'),"\n";}

  • SummaryCGI (Common Gateway Interface) allows you to build dynamic and interactive web pages.Use CGI modules to simplify your designcgi-lib.plcgi.pm

    Each w