Introduction 2 Perl CGI
-
Upload
hasan-pehlivanlar -
Category
Documents
-
view
229 -
download
0
Transcript of Introduction 2 Perl CGI
-
8/7/2019 Introduction 2 Perl CGI
1/31
CGI PerlProgramming
CGI PerlProgramming
Dr. Abzetdin ADAMOV
-
8/7/2019 Introduction 2 Perl CGI
2/31
Overview of Course
Objectives Of The Course
Introduction to CGI
Preparing CGI Programs To Work Calling CGI programs on the client side.
Programming CGI Using PERL
Connecting to and interacting withdatabases using ODBC.
CGI Program Examples
-
8/7/2019 Introduction 2 Perl CGI
3/31
Courses Objectives
To understand how CGI technology works.
To be able to install CGI programs on the
web servers. To identify the ways used to connect client
browsers to CGI Programs
To be able to write CGI programs in PERL To be able to connect to a database and
to run SQL commands.
-
8/7/2019 Introduction 2 Perl CGI
4/31
Introduction to CGI
CGI stands forCommon GatewayInterface.
CGI is a standard programming interfaceto Web servers that gives us a way tomake our sites dynamic and interactive.
CGI is not a programming language. It is
just a set of standards (protocols.) CGI can be implemented in an interpreted
language such as PERL or in a compiledlanguage such as C.
-
8/7/2019 Introduction 2 Perl CGI
5/31
Introduction to CGI(continued)
CGI programs work as follows:
STEP 1 (On the client side): Get
Information from the user (using HTMLforms, SSI, Java Applet, ,etc).
STEP 2 (On the server side): Process thedata, connect to DATABASE, search forPATTERNS, ,etc.
STEP 3 (On the server side): Send theresult of computation back to the client.
-
8/7/2019 Introduction 2 Perl CGI
6/31
Preparing CGI for work
The steps involved in preparing a CGI program for work.
1. Contact your Web host to find out where you shouldput your CGI programs on the server. Usually it will bea directory on the server named cgi-bin.
2. Set up the access permission of directory cgi-binusing the following UNIX command:
chmod 755 cgi-bin/
3. Set up the access permission of the CGI programusing the following UNIX command:chmod 755 cgi-program
4. Test your CGI program from the server command lineto make sure it works perfectly before publishing it.
-
8/7/2019 Introduction 2 Perl CGI
7/31
Calling CGI Programs On The
Client Side
(Using HTML Forms)
. . .
Two HTTP methods are available:
GET
POST
The CGI program will be invoked every time you thebutton SUBMIT is clicked.
See HTMLFormDemo.html
-
8/7/2019 Introduction 2 Perl CGI
8/31
Calling CGI programs on the
client side(Using SSI extensions)
SSI stands forServerSide Includes.
Two ways to invoke a cgi program here:
For SSI to be used , your Web server must be alreadyconfigured to accept SSI extensions.
Usually html files that contain SSI extensions are given theextension .shtm or .shtml.
-
8/7/2019 Introduction 2 Perl CGI
9/31
CGI Programming in PERL
PERL stands forPractical Extraction ReportLanguage.
PERL
Is an interpreted language. Runs on multiple platforms:Windows, Unix, Mac, ,
etc.
Is a scripting language.
Is a typeless language. Has some aspects similar to C language.
Could be as procedural as you want it to be.
Could be as object-oriented as you want it to be(PERL 5).
-
8/7/2019 Introduction 2 Perl CGI
10/31
Introduction to PERL
PERL can be downloaded from:
http://www.perl.com/pub/a/language/info/software.html
To run PERL programs:
On UNIX, type the command from UNIX shell:
perl perl_prog.pl
On Windows, type the command from DOS prompt:
perl perl_prog.pl
PERL is a case-sensitive language just like C or Java.
#sign is used for comments in PERL Example:
#!/usr/bin/perl
# This program is to . . .
-
8/7/2019 Introduction 2 Perl CGI
11/31
Programming Standards
The following coding standards should be followed:
Start the program with a header comment giving info aboutthe PERL path, programmer, copyrights, last modifieddate, and description.
Example:#!/usr/bin/perl
######################################
# Abzetdin Z. Adamov
# Copyrights 2005
# All rights reserved.
#
# Last modified 05/02/2007
# This program is to . . .
######################################
-
8/7/2019 Introduction 2 Perl CGI
12/31
Programming Standards(Continued)
Use three-line-comment style. Example:#
# Incrementing variable $count.
#$count++;
Use meaningful names for variables orsubroutines. Capitalize every word except the
first one. Example:$myBuffer=1;sub printThankYouMessage(){
}
-
8/7/2019 Introduction 2 Perl CGI
13/31
Programming Standards(Continued)
For file handlers such as STDIN, STDOUT useall-cap identifiers.
Use three-space indentation. Example:
## comment here
#
$buffer = '';
foreach $field (@array1){foreach $value (@array2){
$buffer .= "$field: $value\n";
}
}
-
8/7/2019 Introduction 2 Perl CGI
14/31
PERL Data Types
PERL has three built-in data types: scalars,arrays of scalars, and associative arrays ofscalars, known as "hashes".
Scalar Variables A scalar may contain one single value in any of three
different flavors: a number, a string, or a reference.
Scalar values are always named with '$ at thebeginning, even when referring to a scalar that is partof an array or a hash. Examples:$day #A simple scalar value "day"
$day[28] #the 29th element of @day
$day{'Feb'} #The 'Feb' value from %day
-
8/7/2019 Introduction 2 Perl CGI
15/31
PERL Data Type(Continued)
Array Variables
An array is basically a way to store a whole bunch ofscalar values under one name.
An array name begins with an "@" symbol. Examples:
@arrayName = ("element1", "element2");
@browser = ("NS", "IE", "Opera");
@one_two_thre = (1, 2, 3);
To access a single element is an array, use a $+array
name+[ + index+]. Array indexing starts form zero.Examples:
$arrayName[0] # the first element of the
# array
$browser[1] # This will return IE.
-
8/7/2019 Introduction 2 Perl CGI
16/31
PERL Data Type(Continued)
Associative Arrays Hashes Associative arrays are created with a set of
key/value pairs. A key is a text string of your choice
that will help you remember the value later. A hash name begins with % sign. Examples:%hashName = ('key1', 'value1', 'key2','value2');
%ourFriends = ('best', 'Don', 'good','Robert', 'worst', 'Joe');
To access an element, use $+hash name+{+key+}.Examples:$hashName{key1} #This will return value1
$ourFriends{'good'} #This will return
#Robert
-
8/7/2019 Introduction 2 Perl CGI
17/31
Operators
PERL uses: Arithmetic operations: +, -, *, /, %,**.
Relational operations: , =, ==.
String Operations: ., x, eq, ne, lt, gt, le, ge. Assignment Operators: =, +=, -+, *=, /=, .=.
Increment/decrement operators: ++, --.
Boolean operations: &&, ||, !.
Quotation marks: character string with variable interpolation. character string without variable interpolation.
` system commands stings with variable interpolation.
qq|| character string with variable interpolation.
-
8/7/2019 Introduction 2 Perl CGI
18/31
Control Structures
If /else control structure looks like:if(condition){
If body
}
else{Else body
}
Example:if ($gas_money < 10) {
print "You dont have enough money!";
}
else {
print "You have enough money.";
}
-
8/7/2019 Introduction 2 Perl CGI
19/31
Control Structures(Continued)
For loop has the following C-based formula:for (initialize;condition; increment){
code to repeat
}ForExample:
for ($count=1; $count
-
8/7/2019 Introduction 2 Perl CGI
20/31
Control Structures(Continued)
WhileExample:
$count=1;
while ($count < 11){
print "$count\n"; $count++;
}
foreach has the following formula:foreach variable_name (array_name){
code to repeat
}
ForeachExample:
foreach $item(@inventory){
print $item\n;
}
-
8/7/2019 Introduction 2 Perl CGI
21/31
Dealing With Files In PERL
Reading Files: STEP 1: Open the file for reading:
open(DFH, data.txt") || die(Cant Open file);
STEP 2: Read the data from the file:
@rawData = ;
STEP 3: Close the file:close(DFH);
-
8/7/2019 Introduction 2 Perl CGI
22/31
Dealing With Files In PERL(Continued)
Writing to files: STEP 1: Open the file for writing:
open(DFH, >data.txt") || die(Cannot Open file);
STEP 2: Write data to the file:
print DFH New Data;
STEP 3: Close the file:close(DFH);
-
8/7/2019 Introduction 2 Perl CGI
23/31
Dealing With Files In PERL(Continued)
Appending Files: STEP 1: Open the file for appending:
open(DFH, >>data.txt") || die(Cannot Open file);
STEP 2: Write data at the end of the file:
print DFH Another data line;
STEP 3: Close the file:close(DFH);
-
8/7/2019 Introduction 2 Perl CGI
24/31
PERL Subroutines
A subroutine is a named group of statementsthat does a specific job and can be called overand over. Subroutines are very important forsoftware reuse.
The formula of creating subroutines in PERL issub subName(){
group of statements
}
TO call a subroutines as follows:subName(arg1, arg2, arg3, );
PERL pass the arguments to subroutines in anarray named
@_
-
8/7/2019 Introduction 2 Perl CGI
25/31
Useful Built-in Functions
The chop function is used to "chop off" the lastcharacter of a string variableExample: chop(Hii); #return Hi
The length function simply gives you back thenumber of characters in a string variable.Example: length(Hello); #return 5
The substring function is a way to get a portion of
a string value, rather than using the entire value.Example:
$str = substr(Cold, 1, 3); #return old
-
8/7/2019 Introduction 2 Perl CGI
26/31
Useful Built-in Functions(Continued)
The split function separates a string expressioninto a list. Example:my (@pairs) = split(/&/, $buffer);
The translate(tr) function exchanges eachoccurrence of a character in the search stringwith its matching character in the replacementstring. Example: $value =~ tr/+/ /;
The substitute(s///) function searched the searchstring for the input pattern and replaces it withthe replacement pattern. Example:$searchString =~ s/OPattern/NPattern/g;
-
8/7/2019 Introduction 2 Perl CGI
27/31
Regular Expressions
PERL has three primary functions that useregular expressions: split, substitute(s///) andpattern-match(m//).
These functions are used to extract the datasent by the client before processing it on theserver side.
Example:
($name, $value) = split(/=/,$pair);$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
See the handout titled Regular Expressions.
-
8/7/2019 Introduction 2 Perl CGI
28/31
Environment Variable
Associative array %ENV is used to carry on the
information coming from the client. PERL gives you
an access to this variable. Therefore you start your
CGI program by extracting this information.
Name What it Gets
CONTENT_LENGTH Number of characters submitted from a
POST commandHTTP_USER_AGENT Type of Browser viewer is using.
QUERY_STRING String in URL after the ? character
REMOTE_ADDR Remote user's IP address
-
8/7/2019 Introduction 2 Perl CGI
29/31
Database Connection In
PERL
You can use two ways to access a databasefrom a PERL program.
Using DBI Using ODBC
Using ODBC is currently supported by everymajor software company in the world.
In this tutorial, MS Access will be used. Yet itwill still be the same with ODBC whether youconnect to MSACESS, DB2, or any otherdatabase.
-
8/7/2019 Introduction 2 Perl CGI
30/31
Database Connection In PERL
(Continued)
Steps of connecting to a database. STEP 1: Identify the database drivers you
have on you system. STEP 2: Create your database created.
STEP 3: Create DSN (Date Source Name)for your database. You can do that
graphically form the CONTROL PANNEL,or through programming .
STEP 4: Connect to the database usingthe Win32::ODBC module.
-
8/7/2019 Introduction 2 Perl CGI
31/31
CGI Program Examples
PROGRAM 1:Suppose you have a database. You want to connect
to it. What we should do is to create first a DSN.Then you need to connect to the database. Once
you are connected, you can make query to thedatabase using SQL statement. So lets do that.
PROGRAM 2:Suppose that we have a couple of listservs that we
want our user to be able to subscribe orunsubscribe to. We want to create first a GUIinterface (Using HTML form) that will take the theuser information and send it back to the cgiprogram which in turn will send subscription or un-subscription to the listserv on behalf of the user.