Top Banner
CGI Programming CGI Programming September 19, 2001 September 19, 2001 Abdulmalik S. Al-Gahmi Abdulmalik S. Al-Gahmi
31

PowerPoint Presentation

Nov 01, 2014

Download

Documents

Tess98

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: PowerPoint Presentation

CGI ProgrammingCGI Programming

September 19, 2001September 19, 2001

Abdulmalik S. Al-GahmiAbdulmalik S. Al-Gahmi

Page 2: PowerPoint Presentation

Overview of CourseOverview of Course Objectives Of The CourseObjectives Of The Course Introduction to CGIIntroduction to CGI Preparing CGI Programs To WorkPreparing CGI Programs To Work Calling CGI programs on the client side.Calling CGI programs on the client side. Programming CGI Using PERLProgramming CGI Using PERL Connecting to and interacting with Connecting to and interacting with

databases using ODBC.databases using ODBC. CGI Program ExamplesCGI Program Examples

Page 3: PowerPoint Presentation

Course’s ObjectivesCourse’s Objectives To understand how CGI technology works.To understand how CGI technology works. To be able to install CGI programs on the To be able to install CGI programs on the

web servers.web servers. To identify the ways used to connect client To identify the ways used to connect client

browsers to CGI Programs browsers to CGI Programs To be able to write CGI programs in PERLTo be able to write CGI programs in PERL To be able to connect to a database and to To be able to connect to a database and to

run SQL commands.run SQL commands.

Page 4: PowerPoint Presentation

Introduction to CGIIntroduction to CGI CGI stands forCGI stands for Common Gateway Interface Common Gateway Interface.. CGI is a standard programming interface to CGI is a standard programming interface to

Web servers that gives us a way to make Web servers that gives us a way to make our sites dynamic and interactive.our sites dynamic and interactive.

CGI is not a programming language. It is CGI is not a programming language. It is just a set of standards (protocols.) just a set of standards (protocols.)

CGI can be implemented in an interpreted CGI can be implemented in an interpreted language such as PERL or in a compiled language such as PERL or in a compiled language such as C.language such as C.

Page 5: PowerPoint Presentation

Introduction to CGIIntroduction to CGI(continued)(continued)

CGI programs work as follows:CGI programs work as follows:– STEP 1 (On the client side): Get Information STEP 1 (On the client side): Get Information

from the user (using HTML forms, SSI, Java from the user (using HTML forms, SSI, Java Applet, …,etc).Applet, …,etc).

– STEP 2 (On the server side): Process the data, STEP 2 (On the server side): Process the data, connect to DATABASE, search for connect to DATABASE, search for PATTERNS, …,etc.PATTERNS, …,etc.

– STEP 3 (On the server side): Send the result of STEP 3 (On the server side): Send the result of computation back to the client. computation back to the client.

Page 6: PowerPoint Presentation

Preparing CGI for workPreparing CGI for work The steps involved in preparing a CGI program The steps involved in preparing a CGI program

for work.for work.1.1. Contact your Web host to find out where you should Contact your Web host to find out where you should

put your CGI programs on the server. Usually it will put your CGI programs on the server. Usually it will be a directory on the server named “be a directory on the server named “cgi-bincgi-bin”.”.

2.2. Set up the access permission of directory “Set up the access permission of directory “cgi-bincgi-bin” ” using the following UNIX command:using the following UNIX command:

chmod 755 cgi-bin/chmod 755 cgi-bin/3.3. Set up the access permission of the CGI program using Set up the access permission of the CGI program using

the following UNIX command:the following UNIX command: chmod 755 cgi-programchmod 755 cgi-program

4.4. Test your CGI program from the server command line Test your CGI program from the server command line to make sure it works perfectly before publishing it. to make sure it works perfectly before publishing it.

Page 7: PowerPoint Presentation

Calling CGI Programs Calling CGI Programs On The Client SideOn The Client Side

(Using HTML Forms)(Using HTML Forms) <form action=“cgi-prog.cgi” <form action=“cgi-prog.cgi” method=“POST”>method=“POST”>

. . . . . . </form></form>

Two HTTP methods are available:Two HTTP methods are available:– GETGET– POSTPOST

The CGI program will be invoked every time you The CGI program will be invoked every time you the button SUBMIT is clicked.the button SUBMIT is clicked.

See HTMLFormDemo.htmlSee HTMLFormDemo.html

Page 8: PowerPoint Presentation

Calling CGI programs on Calling CGI programs on the client sidethe client side

(Using SSI extensions)(Using SSI extensions) SSI stands for SSI stands for Server Side IncludesServer Side Includes.. Two ways to invoke a cgi program here:Two ways to invoke a cgi program here:

<!--#exec cgi=“cgi_prog.cgi" --> <!--#exec cgi=“cgi_prog.cgi" -->

<!--#exec cmd=“perl cgi_prog.cgi <!--#exec cmd=“perl cgi_prog.cgi arg1 arg2 … " --> arg1 arg2 … " -->

For SSI to be used , your Web server must be For SSI to be used , your Web server must be already configured to accept SSI extensions.already configured to accept SSI extensions.

Usually html files that contain SSI extensions Usually html files that contain SSI extensions are given the extension .shtm or .shtml.are given the extension .shtm or .shtml.

Page 9: PowerPoint Presentation

CGI Programming in CGI Programming in PERLPERL

PERL stands for PERL stands for Practical Extraction Report Practical Extraction Report LanguageLanguage..

PERL PERL – Is an interpreted language.Is an interpreted language.– Runs on multiple platforms:Windows, Unix, Mac, …, etc.Runs on multiple platforms:Windows, Unix, Mac, …, etc.– Is a scripting language.Is a scripting language.– Is a typeless language.Is a typeless language.– Has some aspects similar to C language.Has some aspects similar to C language.– Could be as procedural as you want it to be.Could be as procedural as you want it to be.– Could be as object-oriented as you want it to be (PERL 5).Could be as object-oriented as you want it to be (PERL 5).

Page 10: PowerPoint Presentation

Introduction to PERLIntroduction to PERL PERL can be downloaded from:PERL can be downloaded from:

http://www.perl.com/pub/a/language/info/software.htmlhttp://www.perl.com/pub/a/language/info/software.html To run PERL programs:To run PERL programs:

– On UNIX, type the command from UNIX shell:On UNIX, type the command from UNIX shell:perl perl_prog.plperl perl_prog.pl

– On Windows, type the command from DOS prompt:On Windows, type the command from DOS prompt:perl perl_prog.plperl perl_prog.pl

PERL is a case-sensitive language just like C or Java.PERL is a case-sensitive language just like C or Java. ““#”#”sign is used for comments in PERLsign is used for comments in PERL

– ExampleExample: : #!/usr/bin/perl#!/usr/bin/perl# This program is to . . .# This program is to . . .

Page 11: PowerPoint Presentation

Programming StandardsProgramming Standards The following coding standards should be followed:The following coding standards should be followed:

– Start the program with a header comment giving info about Start the program with a header comment giving info about the PERL path, programmer, copyrights, last modified date, the PERL path, programmer, copyrights, last modified date, and description.and description.

– ExampleExample::#!/usr/bin/perl#!/usr/bin/perl############################################################################# Abdulmalik S. Al-Gahmi# Abdulmalik S. Al-Gahmi# Copyrights © 2001# Copyrights © 2001# All rights reserved.# All rights reserved.### Last modified 9/16/2001# Last modified 9/16/2001# This program is to . . .# This program is to . . .############################################################################

Page 12: PowerPoint Presentation

Programming StandardsProgramming Standards(Continued)(Continued)

Use three-line-comment style. Use three-line-comment style. ExampleExample::### Incrementing variable $count.# Incrementing variable $count.##$count++;$count++;

Use meaningful names for variables or Use meaningful names for variables or subroutines. Capitalize every word except the first subroutines. Capitalize every word except the first one. one. ExampleExample::$myBuffer=1;$myBuffer=1;sub printThankYouMessage(){sub printThankYouMessage(){……}}

Page 13: PowerPoint Presentation

Programming StandardsProgramming Standards(Continued)(Continued)

For file handlers such as STDIN, STDOUT use all-cap For file handlers such as STDIN, STDOUT use all-cap identifiers.identifiers.

Use three-space indentation. Use three-space indentation. ExampleExample::### comment here…# comment here…## $buffer = ''; $buffer = ''; foreach $field (@array1){ foreach $field (@array1){ foreach $value (@array2){ foreach $value (@array2){ $buffer .= "$field: $value\n";$buffer .= "$field: $value\n"; } } }}

Page 14: PowerPoint Presentation

PERL Data TypesPERL Data Types PERL has three built-in data types: scalars, arrays of scalars, PERL has three built-in data types: scalars, arrays of scalars,

and associative arrays of scalars, known as "hashes".and associative arrays of scalars, known as "hashes". Scalar Variables Scalar Variables

– A scalar may contain one single value in any of three different A scalar may contain one single value in any of three different flavors: a number, a string, or a reference.flavors: a number, a string, or a reference.

– Scalar values are always named with '$‘ at the beginning, even Scalar values are always named with '$‘ at the beginning, even when referring to a scalar that is part of an array or a hash. when referring to a scalar that is part of an array or a hash. ExamplesExamples::$day #A simple scalar value "day" $day #A simple scalar value "day" $day[28] #the 29th element of @day$day[28] #the 29th element of @day$day{'Feb'} #The 'Feb' value from %day$day{'Feb'} #The 'Feb' value from %day

Page 15: PowerPoint Presentation

PERL Data TypePERL Data Type(Continued)(Continued)

Array VariablesArray Variables– An array is basically a way to store a whole bunch of An array is basically a way to store a whole bunch of

scalar values under one name.scalar values under one name.

– An array name begins with an "@" symbol. An array name begins with an "@" symbol. ExamplesExamples::@arrayName = ("element1", "element2"); @arrayName = ("element1", "element2");

@browser = ("NS", "IE", "Opera"); @browser = ("NS", "IE", "Opera");

@one_two_thre = (1, 2, 3);@one_two_thre = (1, 2, 3);

– To access a single element is an array, use a $+array To access a single element is an array, use a $+array name+[ + index+]. Array indexing starts form zero. name+[ + index+]. Array indexing starts form zero. ExamplesExamples::$arrayName[0] $arrayName[0] # the first element of the # the first element of the

# array # array

$browser[1] $browser[1] # This will return ‘IE’.# This will return ‘IE’.

Page 16: PowerPoint Presentation

PERL Data TypePERL Data Type(Continued)(Continued)

Associative Arrays “Hashes”Associative Arrays “Hashes”– Associative arrays are created with a set of key/value pairs. A Associative arrays are created with a set of key/value pairs. A

key is a text string of your choice that will help you key is a text string of your choice that will help you remember the value later. remember the value later.

– A hash name begins with % sign. A hash name begins with % sign. ExamplesExamples: : %hashName = ('key1', 'value1', 'key2', %hashName = ('key1', 'value1', 'key2', 'value2'); 'value2');

%ourFriends = ('best', 'Don', 'good', 'Robert', %ourFriends = ('best', 'Don', 'good', 'Robert', 'worst', 'Joe');'worst', 'Joe');

– To access an element, use $+hash name+{+key+}. To access an element, use $+hash name+{+key+}. ExamplesExamples::$hashName{‘key1’} $hashName{‘key1’} #This will return value1#This will return value1$ourFriends{'good'} $ourFriends{'good'} #This will return #This will return #‘Robert’#‘Robert’

Page 17: PowerPoint Presentation

OperatorsOperators PERL uses:PERL uses:

– Arithmetic operations: +, -, *, /, %,**.Arithmetic operations: +, -, *, /, %,**.– Relational operations: <, >, <=, >=, ==. Relational operations: <, >, <=, >=, ==. – String Operations: ., x, eq, ne, lt, gt, le, ge.String Operations: ., x, eq, ne, lt, gt, le, ge.– Assignment Operators: =, +=, -+, *=, /=, .=.Assignment Operators: =, +=, -+, *=, /=, .=.– Increment/decrement operators: ++, --.Increment/decrement operators: ++, --.– Boolean operations: &&, ||, !.Boolean operations: &&, ||, !.– Quotation marks:Quotation marks:

» ”””” character string with variable interpolation.character string with variable interpolation.» ’’’’ character string without variable interpolation.character string without variable interpolation.» ```` system commands stings with variable interpolation. system commands stings with variable interpolation.» qq|…| character string with variable interpolation.qq|…| character string with variable interpolation.

Page 18: PowerPoint Presentation

Control StructuresControl Structures If /else control structure looks like:If /else control structure looks like:

if(condition){if(condition){ If bodyIf body}}else{else{ Else bodyElse body}}

ExampleExample::if ($gas_money < 10) { if ($gas_money < 10) { print "You don’t have enough money!"; print "You don’t have enough money!"; } } else { else { print "You have enough money."; print "You have enough money."; } }

Page 19: PowerPoint Presentation

Control StructuresControl Structures(Continued)(Continued)

For loop has the following C-based formula: For loop has the following C-based formula: for (initialize;condition; increment){ for (initialize;condition; increment){ code to repeat code to repeat }} For ExampleFor Example: : for ($count=1; $count<11; $count++){for ($count=1; $count<11; $count++){ print "cool\n"; print "cool\n"; }}

While loop has also the following C-based formula:While loop has also the following C-based formula:while (test condition) { while (test condition) { code to repeat code to repeat }}

Page 20: PowerPoint Presentation

Control StructuresControl Structures(Continued)(Continued)

While ExampleWhile Example::$count=1; $count=1; while ($count < 11){ while ($count < 11){ print "$count\n"; $count++; print "$count\n"; $count++; }}

foreach has the following formula:foreach has the following formula: foreach variable_name (array_name){ foreach variable_name (array_name){ code to repeat code to repeat }}Foreach ExampleForeach Example::foreach $item(@inventory){foreach $item(@inventory){ print “$item\n”;print “$item\n”;}}

Page 21: PowerPoint Presentation

Dealing With Files In PERLDealing With Files In PERL Reading Files:Reading Files:

– STEP 1: Open the file for reading:STEP 1: Open the file for reading:

open(DFH, “data.txt") || die open(DFH, “data.txt") || die (“Can’t Open file”);(“Can’t Open file”);

– STEP 2: Read the data from the file: STEP 2: Read the data from the file:

@rawData = <DFH>;@rawData = <DFH>;– STEP 3: Close the file:STEP 3: Close the file:

close(DFH);close(DFH);

Page 22: PowerPoint Presentation

Dealing With Files In PERLDealing With Files In PERL(Continued)(Continued)

Writing to files:Writing to files:– STEP 1: Open the file for writing:STEP 1: Open the file for writing:

open(DFH, “>data.txt") || die open(DFH, “>data.txt") || die (“Cannot Open file”);(“Cannot Open file”);

– STEP 2: Write data to the file: STEP 2: Write data to the file:

print DFH “New Data”;print DFH “New Data”;– STEP 3: Close the file:STEP 3: Close the file:

close(DFH);close(DFH);

Page 23: PowerPoint Presentation

Dealing With Files In PERLDealing With Files In PERL(Continued)(Continued)

Appending Files:Appending Files:– STEP 1: Open the file for appending:STEP 1: Open the file for appending:

open(DFH, “>>data.txt") || die open(DFH, “>>data.txt") || die (“Cannot Open file”);(“Cannot Open file”);

– STEP 2: Write data at the end of the file: STEP 2: Write data at the end of the file:

print DFH “Another data line”;print DFH “Another data line”;– STEP 3: Close the file:STEP 3: Close the file:

close(DFH);close(DFH);

Page 24: PowerPoint Presentation

PERL SubroutinesPERL Subroutines A subroutine is a named group of statements that does A subroutine is a named group of statements that does

a specific job and can be called over and over. a specific job and can be called over and over. Subroutines are very important for software reuse.Subroutines are very important for software reuse.

The formula of creating subroutines in PERL isThe formula of creating subroutines in PERL issub subName(){sub subName(){ group of statementsgroup of statements}}

TO call a subroutines as follows:TO call a subroutines as follows:subName(arg1, arg2, arg3, …);subName(arg1, arg2, arg3, …);

PERL pass the arguments to subroutines in an array PERL pass the arguments to subroutines in an array namednamed @_ @_

Page 25: PowerPoint Presentation

Useful Built-in FunctionsUseful Built-in Functions The The chopchop function is used to "chop off" the last function is used to "chop off" the last

character of a string variablecharacter of a string variableExampleExample: : chop(“Hii”);chop(“Hii”); #return “Hi”#return “Hi”

The The lengthlength function simply gives you back the number function simply gives you back the number of characters in a string variable.of characters in a string variable.ExampleExample: : length(“Hello”);length(“Hello”); #return 5 #return 5

The The substringsubstring function is a way to get a portion of a function is a way to get a portion of a string value, rather than using the entire value. string value, rather than using the entire value. ExampleExample::$str = substr(“Cold”, 1, 3);$str = substr(“Cold”, 1, 3); #return “old”#return “old”

Page 26: PowerPoint Presentation

Useful Built-in FunctionsUseful Built-in Functions(Continued)(Continued)

The split function separates a string expression The split function separates a string expression into a list. into a list. ExampleExample::my (@pairs) = split(/&/, $buffer);my (@pairs) = split(/&/, $buffer);

The translate(tr) function exchanges each The translate(tr) function exchanges each occurrence of a character in the search string with occurrence of a character in the search string with its matching character in the replacement string. its matching character in the replacement string. ExampleExample: : $value =~ tr/+/ /;$value =~ tr/+/ /;

The substitute(s///) function searched the search The substitute(s///) function searched the search string for the input pattern and replaces it with the string for the input pattern and replaces it with the replacement pattern. replacement pattern. ExampleExample::$searchString =~ s/OPattern/NPattern/g;$searchString =~ s/OPattern/NPattern/g;

Page 27: PowerPoint Presentation

Regular ExpressionsRegular Expressions PERL has three primary functions that use regular PERL has three primary functions that use regular

expressions: split, substitute(s///) and pattern-expressions: split, substitute(s///) and pattern-match(m//).match(m//).

These functions are used to extract the data sent by the These functions are used to extract the data sent by the client before processing it on the server side.client before processing it on the server side.

ExampleExample::($name, $value) = split(/=/,$pair);($name, $value) = split(/=/,$pair);$value =~ tr/+/ /;$value =~ tr/+/ /;$value =~ $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex(s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;$1))/eg;

See the handout titled “Regular Expressions”.See the handout titled “Regular Expressions”.

Page 28: PowerPoint Presentation

Environment VariableEnvironment VariableAssociative array %ENV is used to carry on the Associative array %ENV is used to carry on the information coming from the client. PERL gives you information coming from the client. PERL gives you an access to this variable. Therefore you start your an access to this variable. Therefore you start your CGI program by extracting this information.CGI program by extracting this information.

NameName What it GetsWhat it Gets

CONTENT_LENGTHCONTENT_LENGTH Number of characters submitted Number of characters submitted from a POST commandfrom a POST command

HTTP_USER_AGENTHTTP_USER_AGENT Type of Browser viewer is using.Type of Browser viewer is using.

QUERY_STRINGQUERY_STRING String in URL after the ? characterString in URL after the ? character

REMOTE_ADDRREMOTE_ADDR Remote user's IP addressRemote user's IP address

Page 29: PowerPoint Presentation

Database Connection In Database Connection In PERLPERL

You can use two ways to access a database from a You can use two ways to access a database from a PERL program.PERL program.– Using DBIUsing DBI

– Using ODBCUsing ODBC

Using ODBC is currently supported by every Using ODBC is currently supported by every major software company in the world.major software company in the world.

In this tutorial, MS Access will be used. Yet it will In this tutorial, MS Access will be used. Yet it will still be the same with ODBC whether you connect still be the same with ODBC whether you connect to MSACESS, DB2, or any other database.to MSACESS, DB2, or any other database.

Page 30: PowerPoint Presentation

Database Connection In Database Connection In PERL PERL (Continued)(Continued)

Steps of connecting to a database.Steps of connecting to a database.– STEP 1: Identify the database drivers you have STEP 1: Identify the database drivers you have

on you system.on you system.– STEP 2: Create your database created.STEP 2: Create your database created.– STEP 3: Create DSN (Date Source Name) for STEP 3: Create DSN (Date Source Name) for

your database. You can do that graphically your database. You can do that graphically form the “CONTROL PANNEL”, or through form the “CONTROL PANNEL”, or through programming .programming .

– STEP 4: Connect to the database using the STEP 4: Connect to the database using the Win32::ODBC module.Win32::ODBC module.

Page 31: PowerPoint Presentation

CGI Program ExamplesCGI Program Examples PROGRAM 1:PROGRAM 1:

Suppose you have a database. You want to connect to it. Suppose you have a database. You want to connect to it. What we should do is to create first a DSN. Then you need What we should do is to create first a DSN. Then you need to connect to the database. Once you are connected, you to connect to the database. Once you are connected, you can make query to the database using SQL statement. So can make query to the database using SQL statement. So let’s do that.let’s do that.

PROGRAM 2:PROGRAM 2:Suppose that we have a couple of listservs that we want our Suppose that we have a couple of listservs that we want our

user to be able to subscribe or unsubscribe to. We want to user to be able to subscribe or unsubscribe to. We want to create first a GUI interface (Using HTML form) that will create first a GUI interface (Using HTML form) that will take the the user information and send it back to the cgi take the the user information and send it back to the cgi program which in turn will send subscription or un-program which in turn will send subscription or un-subscription to the listserv on behalf of the user. subscription to the listserv on behalf of the user.