1 / 25

CGI Programming

CGI Programming. Forms. Forms enable two-way flow of information Three important parts The FORM tag: includes the URL of the scripts that processes the data submitted via the form The Form Elements: like the fields and the menus. Submit button: Sends the data to the CGI script on the server.

cgetz
Download Presentation

CGI Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CGI Programming

  2. Forms • Forms enable two-way flow of information • Three important parts • The FORM tag: includes the URL of the scripts that processes the data submitted via the form • The Form Elements: like the fields and the menus. • Submit button: Sends the data to the CGI script on the server. • Example: < FORM ACTION-http:///www.allScripts.com/cgi-bin/script1.cgi METHOD = POST > <HR> Please share your comments on the form layout <TEXTAREA NAME=“comments” ROWS=3 COLS=65 WRAP> COMMETS</TEXTAREA> </HR> <INPUT TYPE=“submit” VALUE=“PRESS TO SUBMIT”> </FORM>

  3. a) Layout b) script • data can be gathered by a CGI script and saved <form method=“post” action=“http://www.allscripts.com/cgi-bin/script1”>form text </form> <form method=“get” action=“URLofSCRIPT”> form text </form> • single line input (text, checkbox,radio,etc) • multi line input (text) • drop-down menus • HTML Tutorial • Go to the "NCSA--Beginner's Guide to HTML" tutorial located at • http://www.ncsa.uiuc.edu/General/Internet/WWW/HTMLPrimerAll.html • Quick tutorial: http://www.jmarshall.com/easy/cgi/

  4. CGI • CGI: Common Gateway Interface • A simple protocol to communicate between web forms and your program. • Quick tutorial: http://www.jmarshall.com/easy/cgi/ • CGI program can be written in any language that can read from STDIN, write to STDOUT, and access environment variables. e.g., C, Perl, Java, Shell.

  5. CGI Programming 1. Browser requests a URL From the Server. 2. The requested URL is a script. Server executes the script. 3. The CGI script may call other programs. 4. CGI script passes output back to the server. 5. Server passes information back to the browser. 6. Browser formats and displays the information it receives. Browser Server 1 2 5 3 4 CGI-Script Other Programs 6

  6. Typical programming pattern:1. Read input data from STDIN2. Processing the data3. Write the HTML response to STDOUT. When a user submit a form, the sequence of variables are sent to the server in the following format: "name1=value1&name2=value2&name3=value3" Standard CGI script input processing:1. Split the string by "=" and "&”2. Convert all "+" characters to spaces, and You can find input processing funcs in C, Perl, etc on the web. When the http server receives a submission, depending on the submission method of the form, the server construct environment variables and call the CGI program specified by the form. For POST method, the long string can be obtained by reading from STDIN. String length is in environment variable CONTENT_LENGTH. For GET method, the string is in QUERY_STRING GET has length limit. POST is more popular.

  7. Sending HTML response back to user: just write to STDOUTThe first line should be: Content-Type: text/htmlThen write the rest of the HTML contents. • You can send other type of data back to use, such as "Content-type: image/gif" followed by binary gif file data. Not all browsers support all data types. • Sending an existing file to the user as response. Write the following to STDOUT Location: response.html -- followed by a blank line.

  8. A page on the Client Side <A HREF=“http://www.somesite.com/cgi-bin/getDate”> Display Today’s Date”</A> The script, getDate on the Server Side #!/bin/sh echo Content-type: text/plain echo echo "<HTML><HEAD>" echo "<TITLE>getDate </TITLE>" echo "</HEAD><BODY>" today=`/bin/date` echo “<P>Today’s Date: $today</P>” echo "</BODY></HTML>" Example 1

  9. The Client Side <HTML> <HEADER> <TITLE> Is On </TITLE> </HEADER> <BODY> <A HREF="http://www. scu.edu/cgi-bin/isOn.cgi" Is Mary Jones Logged On> </A> </BODY> </HTML> Server side cat isOn.cgi #!/usr/bin/sh echo "Content-type: text/html" echo echo "<HTML><HEAD>" echo "<TITLE>Is On? </TITLE>" echo "</HEAD><BODY>" ison=`who | grep mjones` if [ ! -z "$ison" ] then echo "<P>mjones is logged on.</P>" else echo "<P>mjones NOT logged on</P>" fi echo "</BODY></HTML>" Example 2

  10. #!/usr/local/bin/perl if ($ENV{‘REQUEST_METHOD’} eq ‘GET’){ print “<P> The request method was: $ENV{‘REQUEST_METHOD’}”; print “<P>The data from GET was: $ENV{‘QUERY_STRING’}”;} elsif ( $ENV{‘REQUEST_METHOD’} eq ‘POST’){ read (STDIN,$buffer,$ENV{‘CONTENT_LENGTH’}); } A simple perl script to show the input method used

  11. Parsing Form Input • High-lights of parsing a form input. • The input string should be separated into individual fields (separated by a &). • Field names and values are separated by a =. • Blank spaces encoded as “+” should be converted back to spaces. • Convert special characters encoded as “(x represents a %xx hexadecimal digit) back to their character representation.

  12. int length; char * contentLen, * buffer; char * method = getenv ("REQUEST_METHOD"); printf("Content-type: text/html\n\n"); printf("<html>\n"); if (strcmp(method,"POST") == 0){ printf("<P> POST </P>\n"); contentLen = getenv ("CONTENT_LENGTH"); if (contentLen != NULL){ length = atoi(contentLen); buffer = (char *) malloc (length + 1); if (buffer) if (fread(buffer,1,length,stdin) != length) return; } } printf("<P> Length = %d content = %s</P>\n",length,buffer); printf("</html>\n"); } Assume the form consists of the following fields and the user has input Mary and chosen Two Years <P>Enter Your name: <INPUT TYPE="text" NAME="theName"></P> <UL> <LI> <INPUT TYPE="radio" NAME="years" VALUE="1" > One Year <LI> <INPUT TYPE="radio" NAME="years" VALUE="5"> Two Years ... The string variable, buffer in the program on the left side contains the string theName=Mary&years=5 the string value in buffer should be parsed to separate the fields (and field names and values). Using C For CGI Programs

  13. Perl is an interpreted language for scanning files, extracting information from those text files, and printing reports based on that information. Perl is mainly used to handle text files, but can be used for binary files (databases), process manipulation, network tasks. Runs on DOS and UNIX Information source: http://www.perl.com/perl/ A Simple Perl program #!/usr/bin/perl #This is a comment line print “Hello\n” PERL

  14. Scalar Values $days = 7; Arrays Indexed by numbers @days = ("Mon", "Tues", "Wed" ); Hashes Indexed by key values %days = ("M" => "Monday", "T" => "Tuesday"); %overtime = ($days{"M"},"5", $days{"T"},"10"); print $days{"M"}, "\n"; print "The number of over time hours on ", $overtime{"Monday"}; @daysWorked = @days; $daysWorked = @days; print "Days Worked = ", $daysWorked, " They are : "; print $daysWorked[0], $daysWorked[1], $daysWorked[2]; print "\n"; Data Types

  15. Data Types • Examples@days = (31,28,31,30,31,30,31,31,30,31,30,31); # A list with 12 elements.$#days # Last index of @days; 11 for above list$#days = 7; # shortens or lengthens list @days to 8 elements@days[3,4,5] # = (30,31,30)@days{'a','c'} # same as ($days{'a'},$days{'c'}) • Case is significant--"$FOO", "$Foo" and "$foo" are all different variables. If a letter or underscore is the first character after the $, @, or %, the rest of the name may also contain digits and underscores. If this character is a digit, the rest must be digits.

  16. Processing Arrays • Individual elements in the array can be accessed using the index • Print “Today : $days[5] • Print $days[-1]; # The last item in the array is retrieved • ($day1) = @days # first item • ($day1, $day2) = @days #first two items • $noOfDays = @days #length of the array • Print $#days #prints the last index of the array • Splitting a scalar into an array • @allnames = split (/,/,$nameString) # splits the values in nameString, using the delimiter (comma) and loads the values into the array, allNames

  17. Processing Arrays • @workdays = @days # copies the days array into the array, workDays. • # Retrieving the elements from an array • @result = @workdays [1,2] • @myChoices = (3,4); • @workDays [@myChoices] • unshift (@workdays, $oneMoreDay) # adds oneMoreDay to the beginning of the array • push (@workdays, $oneMoreDay) # adds oneMoreDay to the end of the array • @totaldays = (@days,@workDays) # combines two arrays • @days [1,2] = @twoDays # replaces two elements in the arrays days.

  18. Processing Hashes • A hash (also called associative arrays) contains pairs of associated elements – the key (first) and the value (Second) pairs. • Example: %days = ("M" => "Monday", "T" => "Tuesday"); %overtime = ($days{‘M’},"5", $days{‘T’},"10"); • Values in a hash are identified by a key (not by an index value). • Are important in writing CGI scripts using PERL since the form parsing routines • The data gathered from a form is stored in a hash. • The key in each pair is the NAME attribute – the field name • The value in the pair is the data that the form user has typed in.

  19. Processing Hashes • $oneday = $days {‘M’} #Retrieves the value associated with the key “M”. • @holidays = $days {‘M’,’T’} # retrieves multiple values • @allValues = values (%days); # Retrieves all the values • @allKeys = keys (%days) # retrieves all keys • ($key, $value) = each (%days) #retrieves each pair of key, values • Exists $holidays { ‘M’} #returns a true if the key exists in the hash

  20. Running a PERL command from the command line. perl -e “print ‘Hello, World!’;” A simple PERL program #!/usr/bin/perl print “Enter a line to be displayed on the screen” $input = <STDIN>; print $input; print “Enter first number: “; $num1 = <STDIN> print “Enter second number: “; $num2 = <STDIN>; if ($num1 > $num2) {print “true”;} else {print “false”;} #using a built-in function $strLen = length(“What is the length”); print $strLen; Creating your own functions sub total { $total = 0; foreach $num (@__{ $total += $num; } return $total; } Calling the function total print &total (3,3); PERL - Some Examples

  21. File Processing #The following program reads two lines of data from # the file, “companyData”, prints the total stock value of # each company and the total stock value of all the # companies. $grandTotal = 0; open (STOCKDATA, “companyData.txt”); while ($line = <STOCKDATA>){ chomp ($line); ($compName,$price,$shares) = split (/,/,$line); $totVal = $price * $shares; $grandTotal += $totVal; print “Total value of $compName holdings = $totval\n”; } print “The total value of all stock holdings = $grandTotal\n”; close (STOCKDATA); companyData.txt AlphaBeta,75.0,1032 EastWest,132.00,500 PERL

  22. Example 3: Calculates the total and average grade for each student.The file “grades” contains more than one score for each student. #!/usr/bin/perl open (GRADES, “grades”) or die “Cant open grades: $!\n”; while ($line = <GRADES>) { ($student, $grade) = split (“ “, $line); $grades{$student} .= $grade . “ “; } foreach $student (sort keys %grades) { $scores = 0; $total = 0; @grades = split (“ “, $grades{$student}); foreach $grade (@grades) { $total += $grade; $scores++; } $average = $total / $scores; print “$student: $grades {$student} \t Average: $average\n; }

  23. Conditional Statements • If statement ($Sky, $Space) = ("Blue","Colorless"); if ($Sky eq "Colorless" ){ print " Not so\n"; } elsif ($sky eq "Blue"){ print "Blue Sky \n"; } print $Sky if $Sky; # if statement - a short form • Unless unless ($destination eq "New York" or $destination eq “Chicago"){ print "Destination: $destination\n"; print "No heavy winter clothing may be necessary \n"; }

  24. Loops last - breaks out of the loop #next – is like continue in C $count = 0; LINE: while (<STDIN>)# LINE is a label for the loop {last LINE if /^$/;# Stop on first blank line. # The continue block is not executed because of last next LINE if /^#/;# skip comment lines print $_ ;} continue {$count++;} print $count, "\n";

  25. Loops • Iterates over a list value and sets the control variable to each element of the list. • Examples: @elements = ("Earth", "Sky", "Water", "Space"); $planet = ("Mars","Jupiter","Saturn")[1]; print $planet, "\n"; foreach $element (@elements){ print $element; print "\n";} %days = ("M" => "Monday", "T" => "Tuesday");#create a hash foreach $keyVal (keys %days){ print $keyVal; print "\n"; # prints T M } foreach $val (values %days){ print $val; print "\n"; # prints Tuesday Moday }

More Related