Title: CGI Programming
1CGI Programming
2Forms
- 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
- lt FORM ACTION-http///www.allScripts.com/cgi-bin/s
cript1.cgi METHOD POST gt - ltHRgt Please share your comments on the form
layout - ltTEXTAREA NAMEcomments ROWS3 COLS65 WRAPgt
COMMETSlt/TEXTAREAgt - lt/HRgt
- ltINPUT TYPEsubmit VALUEPRESS TO SUBMITgt
- lt/FORMgt
3- a) Layout b) script
- data can be gathered by a CGI script and saved
ltform methodpost actionhttp//www.allscripts
.com/cgi-bin/script1gtform text lt/formgt - ltform methodget actionURLofSCRIPTgt form
text lt/formgt - 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/HTML
PrimerAll.html - Quick tutorial http//www.jmarshall.com/easy/cgi/
4CGI
- 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.
5CGI 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 pattern1. 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 "name1value1name2value2name3value3" - Standard CGI script input processing1. 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.
8Example 1
- A page on the Client Side
- ltA HREFhttp//www.somesite.com/cgi-bin/getDategt
Display Todays Datelt/Agt
- The script, getDate on the Server Side
- !/bin/sh
- echo Content-type text/plain
- echo
- echo "ltHTMLgtltHEADgt"
- echo "ltTITLEgtgetDate lt/TITLEgt"
- echo "lt/HEADgtltBODYgt"
- today/bin/date
- echo ltPgtTodays Date todaylt/Pgt
- echo "lt/BODYgtlt/HTMLgt"
9Example 2
- Server side
- cat isOn.cgi
- !/usr/bin/sh
- echo "Content-type text/html"
- echo
- echo "ltHTMLgtltHEADgt"
- echo "ltTITLEgtIs On? lt/TITLEgt"
- echo "lt/HEADgtltBODYgt"
- isonwho grep mjones
- if ! -z "ison"
- then
- echo "ltPgtmjones is logged on.lt/Pgt"
- else
- echo "ltPgtmjones NOT logged onlt/Pgt"
- fi
- echo "lt/BODYgtlt/HTMLgt"
- The Client Side
- ltHTMLgt
- ltHEADERgt ltTITLEgt Is On lt/TITLEgt
- lt/HEADERgt
- ltBODYgt
- ltA HREF"http//www. scu.edu/cgi-bin/isOn.cgi" Is
Mary Jones Logged Ongt lt/Agt - lt/BODYgt
- lt/HTMLgt
10A simple perl script to show the input method used
- !/usr/local/bin/perl
- if (ENVREQUEST_METHOD eq GET)
- print ltPgt The request method was ENVREQUEST_M
ETHOD
- print ltPgtThe data from GET was
- ENVQUERY_STRING
- elsif (
- ENVREQUEST_METHOD eq POST)
- read (STDIN,buffer,ENVCONTENT_LENGTH)
-
11Parsing 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.
12Using C For CGI Programs
- Assume the form consists of the following fields
and the user has input Mary and chosen Two Years - ltPgtEnter Your name ltINPUT TYPE"text"
NAME"theName"gtlt/Pgt - ltULgt
- ltLIgt ltINPUT TYPE"radio" NAME"years" VALUE"1"
gt One Year - ltLIgt ltINPUT TYPE"radio" NAME"years"
VALUE"5"gt Two Years - ...
- The string variable, buffer in the program on the
left side contains the string - theNameMaryyears5
- the string value in buffer should be parsed to
separate the fields (and field names and values).
- int length
- char contentLen, buffer
- char method getenv ("REQUEST_METHOD")
- printf("Content-type text/html\n\n")
- printf("lthtmlgt\n")
- if (strcmp(method,"POST") 0)
- printf("ltPgt POST lt/Pgt\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("ltPgt Length d content
slt/Pgt\n",length,buffer) - printf("lt/htmlgt\n")
-
13PERL
- 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
14Data Types
- Scalar Values
- days 7
- Arrays
- Indexed by numbers
- _at_days ("Mon", "Tues", "Wed" )
- Hashes
- Indexed by key values
- days ("M" gt "Monday", "T" gt "Tuesday")
- overtime (days"M","5", days"T","10")
- print days"M", "\n"
- print "The number of over time hours on ",
overtime"Monday"
- _at_daysWorked _at_days
- daysWorked _at_days
- print "Days Worked ", daysWorked, " They are
" - print daysWorked0, daysWorked1,
daysWorked2 - print "\n"
15Data Types
- Examples_at_days (31,28,31,30,31,30,31,31,30,31,30
,31) A list with 12 elements.days
Last index of _at_days 11 for above listdays
7 shortens or lengthens list _at_days to 8
elements_at_days3,4,5 (30,31,30)_at_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 , _at_,
or , the rest of the name may also contain
digits and underscores. If this character is a
digit, the rest must be digits.
16Processing Arrays
- Individual elements in the array can be accessed
using the index - Print Today days5
- Print days-1 The last item in the array is
retrieved - (day1) _at_days first item
- (day1, day2) _at_days first two items
- noOfDays _at_days length of the array
- Print days prints the last index of the array
- Splitting a scalar into an array
- _at_allnames split (/,/,nameString) splits the
values in nameString, using the delimiter (comma)
and loads the values into the array, allNames
17Processing Arrays
- _at_workdays _at_days copies the days array into
the array, workDays. - Retrieving the elements from an array
- _at_result _at_workdays 1,2
- _at_myChoices (3,4)
- _at_workDays _at_myChoices
- unshift (_at_workdays, oneMoreDay) adds
oneMoreDay to the beginning of the array - push (_at_workdays, oneMoreDay) adds oneMoreDay
to the end of the array - _at_totaldays (_at_days,_at_workDays) combines two
arrays - _at_days 1,2 _at_twoDays replaces two elements in
the arrays days.
18Processing Hashes
- A hash (also called associative arrays) contains
pairs of associated elements the key (first)
and the value (Second) pairs. - Example
- days ("M" gt "Monday", "T" gt "Tuesday")
- overtime (daysM,"5", daysT,"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.
19Processing Hashes
- oneday days M Retrieves the value
associated with the key M. - _at_holidays days M,T retrieves multiple
values - _at_allValues values (days) Retrieves all the
values - _at_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
20PERL - Some Examples
- 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 ltSTDINgt
- print input
- print Enter first number
- num1 ltSTDINgt
- print Enter second number
- num2 ltSTDINgt
- if (num1 gt 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 (_at___
- total num
-
- return total
-
- Calling the function total
- print total (3,3)
21PERL
- 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 ltSTOCKDATAgt)
- 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
22Example 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
ltGRADESgt) (student, grade) split ( ,
line) gradesstudent . grade .
foreach student (sort keys grades) scores
0 total 0 _at_grades split ( ,
gradesstudent) foreach grade (_at_grades)
total grade scores average
total / scores print student grades
student \t Average average\n
23Conditional 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" -
24Loops
- last - breaks out of the loop
- next is like continue in C
- count 0
- LINE while (ltSTDINgt) 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"
25Loops
- Iterates over a list value and sets the control
variable to each element of the list. - Examples
- _at_elements ("Earth", "Sky", "Water", "Space")
- planet ("Mars","Jupiter","Saturn")1
- print planet, "\n"
- foreach element (_at_elements)
- print element
- print "\n"
- days ("M" gt "Monday", "T" gt
"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
-