Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 9: Perl and CGI Programming CGI Programming Acknowledgement: Some materials are taken from Teach Yourself CGI Programming with PERL 5 in a Week."— Presentation transcript:

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

2 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

3 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

4 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 (insert text here)

5 HTML Example mypage.html Title of page This is my first homepage. This text is bold

6 HTML Form Please see handout for detailed examples http://cse.unl.edu/~yzhu/cs251/cgi/form_demo.html

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

8 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

9 Hello World hello2.cgi #!/usr/bin/perl print "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.

10 Hello World hello3.cgi #!/usr/bin/perl print "Content-type: text/html\n\n"; $MyDate = `date`; chop $MyDate; print <<"ending_print_tag"; Hello World ; Hello, world! Today is $MyDate ending_print_tag

11 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.

12 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;

13 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/cgi- bin/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 (&).

14 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.

15 HTML Form: Get & Post Syntax: 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.

16 Get example get_demo.html <INPUT TYPE="text" NAME="in" SIZE="20" MAXLENGTH="40" VALUE="hello there"> 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”

17 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"; }

18 Post Example post_demo.html <INPUT TYPE="text" NAME="in" SIZE="20" MAXLENGTH="40" VALUE="hello there"> 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

19 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"; }

20 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"; }

21 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.

22 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

23 Demo for cgi-lib.pl

24 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.

25 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 " 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"; }

26 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


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

Similar presentations


Ads by Google