Download - Cgi
04/12/2023
1
GIRISH SRIVASTAVA
CGICommon Gateway Interface
04/12/2023
2
Objective
After the completion of this training, participants will able to understand about perl scripting and cgi programming aspects.
Topics Covered: Introduction of CGI
The Definition Web Browsing Architecture of CGI How does CGI works Preparing CGI for work
04/12/2023
3
Cont…
Introduction to PerlThe CGI.pm ModulePattern MatchingArraysDealing With Files In PERLBasic HTMLWhat is cgi-lib.pl?Communicating with databasesSending mail with Perl – CGI Scripts
04/12/2023
4
Dynamic Web
When the Web first started, there were only static HTML pages.
The internet had been around for some time already, but it was only after the introduction of HTML.
A lot has happened since then. We would like to place the birth of the dynamic
web to when CGI, Common Gateway Interface, was first introduced in 1993.
CGI was a way to let a website run scripts (usually Perl scripts back then) on the web server and display the output.
04/12/2023
5
Cont…
04/12/2023
6
CGI (Common Gateway Interface)
A standard protocol for interfacing external application software with an information server, usually a web server.
It is basically a set of rules used to describe the way in which a web server communicates with other software housed on the same machine, and then how that software talks back to the web server.
What is returned from the CGI program is based on what was requested, and this information can be accessed and returned to the user in many different ways.
04/12/2023
7
Definition of CGI
The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.
CGI is a standard interface that sits between the web browser and the web server.
When the browser makes a request of the server, all of the request details flow into the server through the input interface of the CGI.
When the server responds with its output, the information flows back out through the output interface of the CGI.
04/12/2023
8
Cont…
CGI programs can be written in any language. Perl is a very common language for CGI
programming as it is largely platform independent and the language’s features make it very easy to write powerful applications.
However, some CGI programs are written in C, shell script, or other languages.
It is important to remember that CGI is not a language in itself.
04/12/2023
9
Some Things to Remember About CGI
CGI is not the program itself.CGI is simply the interface between the Web
page or browser and the Web server that runs the program.
You must have CGI access to run programs on your Web page.
Any program or script that will run on your Web server, can be used as a CGI program.
Most people use Perl to write their CGI scripts, but other languages include C and C++, Tcl, and UNIX shell scripts.
04/12/2023
10
Uses of CGI Scripts
CGI scripts are used to resolve form data, put that data in to databases, send the data out as an email message, respond to the form entry with email or another Web page, and much more.
CGI scripts also are used for behind the scenes interaction with Web readers.
They can set and read cookies, get and tabulate information such as browser and operating system, calculate hit counts, and monitor Web traffic.
04/12/2023
11
Why Use CGI?
Many of the uses of CGI can be duplicated by newer technology such as JavaScript and ActiveX.
The primary benefit to using CGI rather than browser based scripting is that you can be sure that all of your readers (with very few exceptions) will be able to use the program.
Java, JavaScript, and ActiveX can all be turned off within the browser, and many browsers simply don't support them.
Also, it is becoming more common for company firewalls to disallow these technologies to work in their system (often for security or bandwidth reasons).
Because CGI scripts are run on the external Web server, they are not limited by browser or firewall limitations.
04/12/2023
12
Why Not Use CGI?
The biggest drawback to CGI Scripts is that they can put a lot of load on a Web server.
The Web browser will time out (usually after around 5 minutes), but often the server will continue to run the program until a system administrator comes in and shuts off the faulty script.
The browser based scripting tools mentioned above have the advantage of running off the reader's computer.
They use the processor locally rather than on the Web server itself, and so are less intense on the Web server.
04/12/2023
13
Comparing Server-Side Web Languages
Php - Probably currently most popular! But not a general purpose language.
Perl - Older than Php. More difficult to use, but general purpose. Good for general Unix system admin tasks.
ASP.NET - Microsoft’s server-side language; commercial; platform dependent.
Python - Object oriented multi-purpose scripting language. Really good for server-side tasks! But not that well known.
Java Servlets - Java server-side programming, requires Apache Tomcat engine or similar.
JSP - Sun’s version of Java server-side programming.
04/12/2023
14
Java Scripts And Other Web Technologies…
Scripts come in many different formats such as JavaScript, VBScript, ActiveX, Active Server Pages (ASP), Java Applets, JavaBeans, CGI and others.
JavaScript can do some things, however they have limitations and can only work on the client-side.
In other words, the scripts are interpreted and run in the browser of the user.
CGI scripts, on the other hand, will directly interact with the server, where your whole web site resides, simply they are server-side.
Since it works from your server you can take control over the scripts which are running by using other server files (for example the sendmail program of Unix).
04/12/2023
15
Cont…
JavaScripts don't access any of your other files, (for example you cannot access a database which is in your server).
JavaScripts are simply inserted into your HTML pages, which can be run by the browser.
Netscape browsers don't support VBScripts and ActiveX, so are not usually used by the typical web user.
Another technology like ASP can be used instead of CGI but only in a Windows-NT server as UNIX servers do not support them.
Java applets can also be used, however speed can be a problem so many users prefer CGI scripts.
04/12/2023
16
Web Browsing
To understand the concept of CGI, lets see what happens when we click a hyper link to browse a particular web page or URL. Your browser contacts the HTTP web server and
demand for the URL ie. filename. Web Server will parse the URL and will look for the
filename in if it finds that file then sends back to the browser otherwise sends an error message indicating that you have requested a wrong file.
Web browser takes response from web server and displays either the received file or error message.
04/12/2023
17
CGI Architecture Diagram
04/12/2023
18
How does CGI work?
CGI
1. HTTP request
2. Call CGI
3. CGI program’s response
4. HTTP response
User
Web Browser(on client)
Application(on server)
Server
04/12/2023
19
Introduction to CGI(continued)
CGI programs work as follows: STEP 1 (On the client side): Get Information from the
user (using HTML forms,, Java Applet, …,etc). STEP 2 (On the server side): Process the data, connect
to DATABASE, search for PATTERNS, …,etc. STEP 3 (On the server side): Send the result of
computation back to the client.
04/12/2023
20
Preparing CGI for work
The steps involved in preparing a CGI program for work.
1. Contact your Web host to find out where you should put your CGI programs on the server. Usually it will be a directory on the server named “cgi-bin”.
2. Set up the access permission of directory “cgi-bin” using the following UNIX command:
chmod 755 cgi-bin/3. Set up the access permission of the CGI
program using the following UNIX command: chmod 755 cgi-program
4. Test your CGI program from the server command line to make sure it works perfectly before publishing it.
History of Perl
Perl was introduced in 1987reason for its creation was that Mr. Wall was
unhappy by the functionality that sed, C, awk and the Bourne Shell offered him. He looked for a language that will combine all of their best features, while having as
few disadvantages of its own.
Cont… A brief history of Perl
Perl became especially popular as a language for writing server-side scripts for web-servers.
But that's not the only use of perl, as it is commonly used for system administration tasks, managing database data, as well as writing GUI applications.
written by Larry WallA GNU product FREE, Open
Source softwareInterpreted and not compiled!Originally designed for UNIX®,
but is portable to other O/Sstable, cross platform
programming language
Introduction
What does Perl stand for?
‘Perl’ isn’t really an acronym2 favorite expansion:
-- Practical Extraction Report Language-- Pathologically Eclectic Rubbish Lister
It's not PERL or P.E.R.L. 'Perl' refers to the language'perl' to the interpreter that runs the
programs written in Perl
04/12/2023
25
What is Perl and why is it so great?
Perl is a stable, cross platform programming language.Perl stands for Practical Extraction and Report
Language.Perl is a general purpose computer language ideally
suited to handling words and text.The quote of Perl gurus, “It makes the easy things
easy, and the difficult things possible.”Perl's strengths is that there are usually many ways of
accomplishing any particular bit of programming.This strength inspires Perl programmers to quote the
motto "TIMTOWTDI" (pronounced "timtoady") - the acronym of "There Is More Than One Way To Do It."
Perl Features
Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others.
Perls database integration interface (DBI) supports third-party databases including Oracle, MySQL and others.
works with HTML, XML, and other mark-up languages.
Cont… Perl Features
supports Unicode. supports both procedural and OO
programming. extensible. The Perl interpreter can be embedded into
other systems.
Perl & the Web
Perl is the most popular web programming language due to its text manipulation capabilities and rapid development cycle.
Perl is widely known as "the duct-tape of the Internet".
Perl's CGI.pm module, part of Perl's standard distribution, makes handling HTML forms simple.
Perl can handle encrypted Web data, including e-commerce transactions.
Cont… Perl and the Web
Perl can be embedded into web servers to speed up processing by as much as 2000%.
mod_perl allows the Apache web server to embed a Perl interpreter.
Perl's DBI package makes web-database integration easy. mod_perl is an optional module for the Apache HTTP server. It embeds a Perl interpreter into the Apache server, so that dynamic content produced by Perl scripts can be served in response to incoming requests, without the significant overhead of re-launching the Perl interpreter for each request.
04/12/2023
30
What is needed to run Perl CGI programs?
There are several things you need in order to create and run Perl CGI programs. a web server web server configuration which gives you
permission to run CGI a Perl interpreter appropriate Perl modules, such as CGI.pm a shell account is extremely useful but not
essential
04/12/2023
31
Setting up Perl/CGI
First, you need to get Perl if you do not already have it installed.
Go to http://www.activestate.com/Products/ActivePerl/Download.html and download the latest release for Windows.
Next, you need a Web server.http://httpd.apache.org/download.cgiScroll down to locate Win32 Binary without
crypto (no mod_ssl) (MSI Installer).http://www.webdevelopersnotes.com/how-do-i/install-apache-windows-7.php
04/12/2023
32
First CGI Program
#!C:\Perl\bin\perl.exe use CGI; print "Content-Type: text/html\n\n"; print "<HTML>\n"; print "<HEAD>\n"; print "<TITLE>Hello World</TITLE>\n"; print "</HEAD>\n"; print "<BODY>\n"; print "<H4>Hello World</H4>\n"; print "<P>\n"; print "Your IP Address is $ENV{REMOTE_ADDR}.\n"; print "<P>"; print "<H5>Have a nice day</H5>\n"; print "</BODY>\n"; print "</HTML>\n";
04/12/2023
33
Explanation
The first line of your program should look like this: #!C:\Perl\bin\perl -wT The first part of this line, #!, indicates that this is a script. The
next part, C:\Perl\bin\perl.exe, is the location (or path) of the Perl interpreter.
The final part contains optional flags for the Perl interpreter. Warnings are enabled by the -w flag. Special user input taint checking is enabled by the -T flag. Taint mode tells Perl to keep track of data that comes from the user and avoid doing anything insecure with it.
print "Content-type: text/html\n\n"; This is a content-type header that tells the receiving web
browser what sort of data it is about to receive — in this case, an HTML document. If you forget to include it, or if you print something else before printing this header, you'll get an "Internal Server Error" when you try to access the CGI program.
04/12/2023
34
Introduction to PERL
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 . . .
04/12/2023
35
Programming Standards
The following coding standards should be followed: Start the program with a header comment giving info
about the PERL path, programmer, copyrights, last modified date, and description.
Example:#!/usr/bin/perl####################################### Girish Srivastava# Copyrights © 2001# All rights reserved.## Last modified 9/16/2001# This program is to . . .######################################
04/12/2023
36
Programming Standards(Continued)
Use three-line-comment style. Example:## Incrementing variable $count.#$count++;
Use meaningful names for variables or subroutines. Capitalize every word except the first one. Example:$myBuffer=1;sub printThankYouMessage(){…}
04/12/2023
37
PERL Data Types
PERL has three built-in data types: scalars, arrays of scalars, and associative arrays of scalars, 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 the
beginning, even when referring to a scalar that is part of 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
04/12/2023
38
PERL Data Type(Continued)
Array Variables An array is basically a way to store a whole bunch
of scalar 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’.
04/12/2023
39
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’
04/12/2023
40
Example
#!C:\Perl\bin\perl.exemy $text = 'cool guy';my $string = "some $text";print $string; # prints literally “some cool
guy”;
Arrays
#!C:\Perl\bin\perl -w#DEFINE SOME ARRAYS@days = ("Monday", "Tuesday", "Wednesday");@months = ("April", "May", "June");#PRINT MY ARRAYS TO THE BROWSERprint @days;print @months;
Hashes
#!C:\Perl\bin\perl -w#DEFINE SOME HASHES%hashName = ('key1', 'value1', 'key2', 'value2'); %ourFriends = ('best', 'Don', 'good', 'Robert', 'worst', 'Joe'); #PRINT MY HASHES TO THE BROWSERprint $hashName{'key1'};print $ourFriends{'good'};
04/12/2023
41
Operators
PERL uses: Arithmetic operations: +, -, *, /, %,**. Relational operations: <, >, <=, >=, ==. String Operations: 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.
#!C:\Perl\bin\perl.exe$one = 1;$two = 2;$three = 3;$four = 4;$abcd = "abcd";$pqrs = "pqrs";$xyz = "xyz";
# concantenate the two strings and printprint $abcd . " another string\n"; # repeat the string abcd three timesprint $abcd x $three . "\n"; # add the data in variables one and two. The numerical value is converted to string and concantenated with \n print $one + $two . "\n";
print $three % $two . "\n"; # modulo - returns the remainder of three divided by twoprint $three ** $two . "\n";# exponentiation - three raised to power twoprint $one++ . "\n"; # post incrementprint ++$one . "\n";# pre incrementprint $one-- . "\n"; # post decrementprint --$one . "\n"; # pre decrement$one += $two;# $one = $one + $two$one -= $two;# $one = $one - $two
04/12/2023
42
Control Structures
Control structures include conditional statements, such as if/elsif/else blocks, as well as loops like foreach, for and while. if ($varname > 23) { # do stuff here if the condition is
true }
if ($varname > 23) { print "$varname is greater than 23"; } elsif ($varname == 23) { print "$varname is 23"; } else { print "$varname is less than 23"; }
#!C:\Perl\bin\perl.exemy $number = 95;if($number eq 92){ print 'Number is ninety-five!';}else{ print 'Number is not ninety-five';}
04/12/2023
43
Unless
unless is similar to if. Let's say you wanted to execute code only if a certain condition were false. You could do something like this: if ($varname != 23) { # code to execute if $varname is not
23 }
The same test can be done using unless: unless ($varname == 23) { # code to execute if $varname is
not 23 }
There is no "elseunless", but you can use an else clause: unless ($varname == 23) { # code to execute if $varname is not 23 } else { # code to execute if $varname IS 23 }
04/12/2023
44
Looping
Loops allow you to repeat code for as long as a condition is met. Perl has several loop control structures: foreach, for, while and until.
Foreach Loops foreach iterates through a list of values:
foreach my $i (@arrayname) { # code here }
This loops through each element of @arrayname, setting $i to the current array element for each pass through the loop. You may omit the loop variable $i: foreach (@arrayname) { # $_ is the current array element }
This sets the special Perl variable $_ to each array element. $_ does not need to be declared (it's part of the Perl language) and its scope localized to the loop itself.
04/12/2023
45
Cont…
For Loops Perl also supports C-style for loops:
for ($i = 1; $i < 23; $i++) { # code here }
While Loops A while loop executes as long as particular condition is true:
while (condition) { # code to run as long as condition is true }
Until Loops until is the reverse of while. It executes as long as a particular
condition is NOT true: until (condition) { # code to run as long as condition is not true }
#!C:\Perl\bin\perl.exe@array = ("value1", "value2", 1, 2, 3, 4);foreach my $value (@array){ print $value;}
#!C:\Perl\bin\perl.exe$integer = 0;while($integer < 50){ print $integer; $integer++;}
Until
#!C:\Perl\bin\perl.exe$firstVar = 10; until ($firstVar > 12) { print("inside: firstVar = $firstVar\n"); $firstVar++; } print("outside: firstVar = $firstVar\n");
This program displays:inside: firstVar = 10 inside: firstVar = 11 inside: firstVar = 12 outside: firstVar = 13
04/12/2023
46
Exercise
1. Create a program using PERL, which gives the output as per the following figure:
** *
* * ** * * *
* * * * *
04/12/2023
47
Breaking from Loops
There are several ways to break from a loop. To stop the current loop iteration (and move on to the next one), use the next command: foreach my $i (1..20) { if ($i == 13) { next; } print "$i\n"; }
This example prints the numbers from 1 to 20, except for the number 13. When it reaches 13, it skips to the next iteration of the loop.
To break out of a loop entirely, use the last command: foreach my $i (1..20) { if ($i == 13) { last; } print "$i\n"; }
This example prints the numbers from 1 to 12, then terminates the loop when it reaches 13.
04/12/2023
48
Cont…
next and last only effect the innermost loop structure, so if you have something like this:
foreach my $i (@list1) { foreach my $j (@list2) { if ($i == 5 && $j == 23) { last; } } # this is where that last sends you }
The last command only terminates the innermost loop. If you want to break out of the outer loop, you need to use loop labels:
OUTER: foreach my $i (@list1) { INNER: foreach my $j (@list2) { if ($i == 5 && $j == 23) { last OUTER; } } } # this is where that last sends you
The loop label is a string that appears before the loop command (foreach, for, or while). In this example we used OUTER as the label for the outer foreach loop and INNER for the inner loop label.
04/12/2023
49
The CGI.pm Module
Perl offers a powerful feature to programmers: add-on modules.
These are collections of pre-written code that you can use to do all kinds of tasks.
Some modules are included as part of the Perl distribution; these are called standard library modules and don't have to be installed. If you have Perl, you already have the standard library modules.
04/12/2023
50
Cont…
Let's see how to use a module in your CGI program. First you have to actually include the module via the use command. This goes after the #!C:\Perl\bin\perl.exe line and before any other code: use CGI qw(:standard);
Note :we're not doing use CGI.pm but rather use CGI. The .pm is implied in the use statement. The qw(:standard) part of this line indicates that we're importing the "standard" set of functions from CGI.pm.
Now you can call the various module functions by typing the function name followed by any arguments: functionname(arguments)
04/12/2023
51
Cont…
A function is a piece of code that performs a specific task; it may also be called a subroutine or a method.
Functions may accept optional arguments (also called parameters), which are values (strings, numbers, and other variables) passed into the function for it to use.
The CGI.pm module has many functions; for now we'll start by using these three:
header; start_html; end_html;
04/12/2023
52
Cont…
The header function prints out the "Content-type" header. With no arguments, the type is assumed to be "text/html".
start_html prints out the <html>, <head>, <title> and <body> tags. It also accepts optional arguments. If you call start_html with only a single string argument, it's assumed to be the page title. For example: print start_html("Hello World");
will print out the following*: <html> <head> <title>Hello World</title> <head> <body>
04/12/2023
53
Cont…
The end_html function prints out the closing HTML tags:
</body> </html>
#!C:\Perl\bin\perl.exe use CGI qw(:standard); print header; print start_html("Hello World"); print "<h2>Hello, world!</h2>\n"; print end_html;
04/12/2023
54
Basic HTML
HyperText Markup Language
HTML is the language used to prepare hypertext document.
Web browsers are used to view HTML documents and display data to users
04/12/2023
55
HTML Document
<html><head><title>Test Page</title></head><body><b>Hello, world</b> </body></html>
Document Structure- Head- Body
04/12/2023
56
HTML Tags
HTML tags are commands, they tell the browser how to display the text.
There are opening and closing versions for many tags
opening tag: <HTML>closing tag: </HTML>
04/12/2023
57
HTML Tags (continued)
<HTML></HTML> For identifying a text document as an HTML document
<HEAD></HEAD> For creating the head section of page <BODY></BODY> For enclosing the main section of page <B></B> For displaying text in boldface <I></I> For displaying text in italics <OL></OL> For creating ordered lists <A></A> For creating links <FORM></FORM> For creating fill-in forms <P> For creating a new paragraph <BR> For creating a line break <INPUT> For creating form elements
04/12/2023
58
HTML Tags (continued)
The affected text is contained within the tags<B>Hello</B> ------- Hello<I>Bye!</I> ---------- ByeOrdered list
<OL><LI>Apple</LI><LI>Banana</LI><LI>Orange</LI></OL>
1. Apple2.
Banana3.
Orange
04/12/2023
59
HTML Form
<FORM> and </FORM> mark the beginning and the end of a form
Form establishes the relationship between the form page and the script that will process the current form data
HTML forms are the user interface that provides input to your CGI scripts
- Collecting data- Accepting commands
04/12/2023 60
HTML Form (continued)
<HTML><HEAD><TITLE>My first html
page</TITLE></HEAD><BODY><FORM method=post
action=“aftersubmit.cgi”>Name: <INPUT type=text
name=“uname"><BR>Password: <INPUT type=password
name=“upwd"><BR><INPUT type=submit><INPUT type=reset></FORM></BODY></HTML>
04/12/2023
61
The <FORM> Tag
<FORM method=post action=“aftersubmit.cgi”> Tag attributes specify the properties for the element
Method determines how the form data is sent to the script
- GET-- delivers form data by appending it to the URL of the script
- POST-- sends the data as a body of textaction
specifies the address of the script that is going to process the current form data
04/12/2023
62
The <INPUT> Tags
INPUT- is an element of the form - creates a wide variety of interface widgets
<INPUT type=text name=“uname">Attribute “type”— the appearance and
features <INPUT type=text>-------text field <INPUT type=submit>-----submit
button <INPUT type=reset>------reset button
<INPUT type=password>---password
field <INPUT type=hidden>-----hidden
field
04/12/2023
63
The <INPUT> Tag (continued)
INPUT attribute "name" identifies each user interface element
<input type=text name=“uname"><input type=password
name=“upwd"> INPUT attribute "value"
contains associated information that is also sent to the script. <input type=text name=“uname"> <input type=text name=“uadd"> <input type=text name=“ucity“
value=“Edmonton”>
04/12/2023
64
Form Submission
<FORM method=post action = “aftersubmit.cgi”>
The browser assembles the form data (name and password) into a series of name/value pairs
The browser delivers data to the server and then the script “aftersubmit.cgi”
The script “aftersubmit.cgi” can retrieve the element value by using its name (uname and upwd)
04/12/2023
65
Forms: Checkbox
Checkboxes allow the viewer to select one or more options on a form. If you assign each checkbox field a different name, you can print them the same way you'd print any form field using param('fieldname').
Here is the HTML code for a set of checkboxes: <b>Pick a Color:</b><br> <form action="colors.cgi" method="POST"> <input type="checkbox" name="red" value=1> Red<br> <input type="checkbox" name="green" value=1> Green<br> <input type="checkbox" name="blue" value=1> Blue<br> <input type="checkbox" name="gold" value=1> Gold<br> <input type="submit"> </form>
This example lets the visitor pick as many options as they want — or none, if they prefer. Since this example uses a different field name for each checkbox, you can test it using param: my @colors = ("red","green","blue","gold"); foreach my $color (@colors) { if (param($color)) { print "You picked $color.\n"; } }
04/12/2023
66
Cont…
Since we set the value of each checkbox to 1 (a true value), we didn't need to actually see if param($color) was equal to anything — if the box is checked, its true. If it's not checked, then param($color) is undefined and therefore not true.
The other way you could code this form is to set each checkbox name to the same name, and use a different value for each checkbox: <b>Pick a Color:</b><br> <form action="colors.cgi" method="POST"> <input type="checkbox" name="color" value="red"> Red<br> <input type="checkbox" name="color" value="green"> Green<br> <input type="checkbox" name="color" value="blue"> Blue<br> <input type="checkbox" name="color" value="gold"> Gold<br> <input type="submit"> </form>
04/12/2023
67
Cont…
param('color') returns a list of the selected checkboxes, which you can then store in an array. Here is how you'd use it in your CGI program: my @colors = param('color'); foreach my $color (@colors) { print "You picked $color.<br>\n"; }
04/12/2023
68
Radiobutton
<b>Pick a Color:</b><br> <form action="colors.cgi" method="POST"> <input type="radio" name="color" value="red"> Red<br> <input type="radio" name="color" value="green"> Green<br> <input type="radio" name="color" value="blue"> Blue<br> <input type="radio" name="color" value="gold"> Gold<br> <input type="submit"> </form>
Cgi code:Since the viewer can only choose one item
from a set of radio buttons, param('color') will be the color that was picked: my $color = param('color'); print "You picked $color.<br>\n";
04/12/2023
69
Basic Setup
That's the basic set up for a CGI form, but what happens after the user presses Submit? Consider, for example, this simple form: Name:
E-mail: SUBMIT
Here's the chain of events when the user hits "Submit":
04/12/2023
70
Cont…
04/12/2023
71
Cont…
When the user presses Submit, the browser sends the form data to the web server.
The web server launches the CGI program which was written to process this form.
The CGI program does whatever it does with the data. The program might consult a database, perform calculations on the data, use the data to add the user to a mailing list, whatever the programmer wants it to do. Whatever else the program does, it generates a web page using HTML so the user can see the results of submitting the form.
The CGI program passes the HTML back to the web server. The web server passes the HTML back to the browser.
So there are three pieces to the CGI process: the form on your web page, the web server, and the CGI program.
04/12/2023
72
Exercise
04/12/2023
73
Exercise
Create an html form having multiple radio buttons showing different different colors. If you select any of the radio button and press submit, then it will call appropriate cgi page and the background color of that page will be same as the color which you have selected from the list.
04/12/2023
74
Pattern Matching
Almost every script you write in Perl will have some kind of pattern matching operation .
Patterns are subject to an additional level of interpretation as a regular expression. This is done as a second pass, after variables are interpolated.
To use pattern matching in Perl, first we figure out what we want to find, we write a regular expression to find it, and then we stick that pattern in a situation where the result of finding.
04/12/2023
75
Cont…
The Binding Operator When you do a pattern match, you need three things:
the text you are searching through the pattern you are looking for a way of linking the pattern with the searched text
As a simple example, let's say you want to see whether a string variable has the value of "success". Here's how you could write the problem in Perl: $word = "success"; if ( $word =~ m/success/ ) { print "Found success\n"; } else { print "Did not find success\n"; }
04/12/2023
76
Cont…
There are two things to note here. First, the "=~" construct, called the binding operator, is
what binds the string being searched with the pattern that specifies the search. The binding operator links these two together and causes the search to take place.
Next, the "m/success/" construct is the matching operator, m//, in action. The "m" stands for matching to make it easy to remember. The slash characters here are the "delimiters". They surround the specified pattern. In m/success/, the matching operator is looking for a match of the letter sequence: success.
Generally, the value of the matching statement returns 1 if there was a match, and 0 if there wasn't.
04/12/2023
77
Regular Expressions
Regular expressions are very powerful tools for matching, searching, and replacing text.
All pattern matching in Perl is based on this concept of regular expressions.
Regular expressions form a standard way of expressing almost any text pattern unambiguously.
Special CharactersSome special characters or combinations of
characters have a special meaning and do not represent themselves.
This is what give regular expressions their power. For example, the lowly period does not stand for a
period in a match. Instead, it stands for any character.
04/12/2023
78
Cont…
The pattern /b.g/ would match "bag", "big", "bug", etc, as well as any other sequence: "b2g", "b&g", "b]g" and so on.
Matching simply means "found somewhere, anywhere, within the searched string".
You can use special characters to specify the position where the search pattern must be located. A ^ character stands for the beginning of the searched string, so:
/^success/ would match "success" but not "unsuccessful". A $ character stands for the end of the searched string, so:
/success$/ would match "unsuccess" but not "successful". Using both ^ and $ together nails the pattern down at both ends, so:
/^success$/ will only match the exact string "success".
04/12/2023
79
Cont…
Other special characters include: \ - a form of a "quote" character
| - alternation, used for "or'ing"() - grouping matched elements[] - character class
The first character, "\", is used in combination with special letters to take away their special meaning. E.g.: \. will match a period
\$ will match a dollar sign\^ will match a caret\\ will match a backslash
and so on.
04/12/2023
80
Cont…
Repetition CharactersThe expressions above show you how to
match certain characters, but they don't allow you to control how many matches should be made at once. Matching repetition is controlled by a few other special characters: + means 1 or more matches
* means 0 or more matches? means 0 or 1 matches{n} exactly n matches{m,n} m to n matches
04/12/2023
81"Hello world!" to be changed to "Hello mom!" instead.
$mystring =~ s/world/mom/; print $mystring;
Prints "Hello mom!". The substitution operator s/// replaces the pattern between the s/ and the middle /, with the pattern between the middle / and last /. In this case, "world" is replaced with the word "mom".
Now change "Hello mom!" to say "Goodby mom!". $mystring =~ s/hello/Goodbye/; print $mystring;
This does not substitute, and prints "Hello mom!" as before. By default, the search is case sensitive. As before, use the pattern modifier i immediately after the trailing / to make the search case-insensitive.
Okay, ignoring case, change "Hello mom!" to say "Goodby mom!". $mystring =~ s/hello/Goodbye/i; print $mystring;
Prints "Goodby mom!".
04/12/2023
82
Process form with regular expression: first name and last name
<html><head><title>form page</title></head><body><p>here's my test form</p><form method = "post" action = "/cgi-bin/RegExpExample.cgi"><p>First name: <input name = "firstName" type = "text" size = "20"></p><p>Last name: <input name = "lastName" type = "text" size = "20"></p><p>Phone number: <input name = "phone" type = "text" size = "20"></p><p>Date (MM/DD/YY): <input name = "date" type = "text" size = "20"></p><p>Time (HH:MM:SS): <input name = "time" type = "text" size = "20"></p><input type = "submit" value = "submit"><input type = "reset" value = "reset"></form></body></html>
04/12/2023
83
Cont…
#!C:\Perl\bin\perl.exe use strict; use warnings; use CGI ':standard'; my $firstName = param( "firstName" ); my $lastName = param( "lastName" ); my $phone = param( "phone" ); my $date = param( "date" ); my $time = param( "time" ); print header(); print start_html( -title => "form page" ); if ( $firstName =~ /^\w+$/ ) { print "<p>Hello there \L\u$firstName.</p>"; } if ( $lastName =~ /^\w+$/ ) { print "<p>Hello there Mr./Ms. \L\u$lastName.</p>"; } print end_html();
04/12/2023
84
Arrays
An array stores an ordered list of values. While a scalar variable can only store one value, an array can store many. Perl array names are prefixed with an @-sign. Here is an example: my @colors = ("red","green","blue");
Each individual item (or element) of an array may be referred to by its index number. Array indices start with 0, so to access the first element of the array @colors, you use $colors[0].
when you're referring to a single element of an array, you prefix the name with $ instead of @. The $-sign again indicates that it's a single (scalar) value; the @-sign means you're talking about the entire array.
04/12/2023
85
Cont…
If you want to loop through an array, printing out all of the values, you could print each element one at a time: my @colors = ("red","green","blue"); print "$colors[0]\n"; # prints "red" print "$colors[1]\n"; # prints "green" print "$colors[2]\n"; # prints "blue"
A much easier way to do this is to use a foreach loop: my @colors = ("red","green","blue"); foreach my $i (@colors) { print "$i\n";}
04/12/2023
86
Finding the Length of Arrays
If you want to find out how many elements are in a given array, you can use the scalar function: my @people = ("Howard", "Sara", "Ken", "Josh"); my $linelen = scalar(@people); print "There are $linelen people in line.\n";
Sorting ArraysYou can do an alphabetical (ASCII) sort on an
array of strings using the sort function: my @colors = ("cyan", "magenta", "yellow", "black"); my @colors2 = sort(@colors);
04/12/2023
87
Dealing With HTML Components in perl-cgi
We can create html form component like: textbox, textarea, buttons, etc, in CGI.
use strict;use warnings;use CGI;my $cgi=new CGI;print $cgi->header(),$cgi->start_html("Simple Examples");print $cgi->center("Centered Text");print $cgi->p("A Paragraph");print $cgi->br();print $cgi->b("Bold"),$cgi->i("Italic");print $cgi->p("A Paragraph",$cgi->sup("A superscript"));print $cgi->end_html();
04/12/2023
88
Form Example
use CGI;
$co = new CGI;
print $co->header,
$co->start_html(-title=>'CGI Example'),
$co->center($co->h1('Welcome to CGI!')),
$co->start_form(),
$co->textarea( -name=>'textarea', -rows=>10, -columns=>60),
$co->end_form(),
$co->end_html;
#!C:\Perl\bin\perluse CGI ':standard';print header();print "Form Elements", br(), br(), br();print start_form;print "A Text Box: ", textfield('surname', 'Default', 50), br(); print "A Select Box: ", popup_menu('SelectBox', ['Perl', 'Web', 'Development']); print p, "Text Area: ", textarea('comments', 'Default Text', 10, 50);print p, "CheckBoxes: ", checkbox_group('check1', ['one', 'two', 'three']);print p, "Radio Buttons: ", radio_group('radio1', ['a', 'b', 'c']);print p, submit();print end_form;if (param()) { print "The surname you entered was: ",em(param('surname')), p, "The Selections are: ",em(join(", ",param('SelectBox'))), p, "The comments box contains: ",em(param('comments')), p, "you selected checkbox: ",em(param('check1')), p, "you selected radio: ",em(param('radio1'));}
04/12/2023
89
Dealing With Files In PERL
Reading Files: STEP 1: Open the file for reading:open(DFH, “data.txt") || die (“Can’t Open file”);
STEP 2: Read the data from the file: @rawData = <DFH>; STEP 3: Close the file:close(DFH);
04/12/2023
90
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);
04/12/2023
91
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);
04/12/2023
92
Reading Data File
When you build large web application, you will need to store data and retrieve it later
Text files are the simplest way to maintain data
04/12/2023
93
Reading And Writing Data File (script)
#!C:\Perl\bin\perl.exe open(SRC, “file.txt”) || die “Could not open
source file.\n”;open(DST, “>newfile.txt”);while ( $line = <SRC> )
{ print DST $line;
}close SRC;close DST;
04/12/2023
94
File Handle
The file handles are just the things we use when we are dealing with files.
A file handle is associated with a file by the open statement.
open (FILE, $filename) All the interaction with a file is done by the
file handle. @filecontent = <FILE> -- get the
whole file$filecontent = <FILE> ---- get the first
line
04/12/2023
95
Writing Data File
#!C:\Perl\bin\perl.exeuse CGI; $q=new CGI;print "Content-type: text/html\n\n";my $name=$q->param("name");
my $outputfile="users.txt";if (open (OUTPUT, ">>$outputfile")) # open a file{ print OUTPUT "$name\n"; # write the user
name to the file print "<HTML><BODY>Thank you!
$name</BODY></HTML>";}
<html><head></head><body><form action="/cgi-bin/FileRead_Html.cgi"
method="post"><input type="text" name="name"><input type="submit" name="submit" value="Go"></form></body></html>
04/12/2023
96
Writing Data File (continued)
Opening a file for writing - For overwriting
open (OUTPUT, ">>$outputfile") - For appending
open (OUTPUT, ">$outputfile") Without “>>” and “>”, the file is opened for
reading open (OUTPUT, "$outputfile")
Creating the output file and making it writable
touch users.txtchmod a+w users.txt
04/12/2023
97
Exercise
Create a login page using perl-cgi script, read the user name and password from existing .txt file. After pressing the submit button it should show the Message of successful or unsuccessful login.
Write a Perl script that will take as input a file called “foo.txt”, produce as output a file called “bar.txt”; lines in input will be copied to output, except for the following transformations: any line with the string “IgNore” in it will not go to output any line with the string “#” in it will have that character
and all characters after it, to end of line, removed any string “*DATE*” will be replaced by the current date in
output •We have a file containing lines in different formats. We want to pick out the lines which start with a digit and end in a period.
04/12/2023 98
Debugging
Default response of the server: "Internal Server Error" --- not useful
Better ways:
In the scriptuse CGI::Carp qw(fatalsToBrowser);
In the UNIX shell (check the syntax)perl -cw scriptname.cgi
see the error in your browser instead of the error logs
If you want to do a similar thing with Perl warnings as well, use this instead:use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
04/12/2023 99
Debugging (continued)
use CGI::Carp qw(fatalsToBrowser);
04/12/2023
100
What is cgi-lib.pl?
Cgi-lib is a CGI parsing library written by Steven Brenner. The cgi-lib.pl library that was become the first standard perl
library to help parse and deal with CGI Web based interfaces. The cgi-lib.pl library makes CGI scripting in Perl easy enough for
anyone to process forms and create dynamic Web content. The library has the following features:
Extremely simple to learn and easy to use Designed for operation under Perl5 and Perl4 Very efficient Compatibility with all CGI interactions Compatible with Perl5 security features such as taint, warnings,
(command line options -Tw) and use strict; Debugging facilities
04/12/2023
101
Cont…
The cgi-lib.pl Perl library simply consists of handy, easy-to-use Perl functions. The library is more than simply a means of processing CGI input. The library includes subroutines to:
Read and parse CGI input -- a value(s) for a given name can be easily found.
Conveniently format CGI output. Conveniently return Headers and Bottoms of standard CGI output. Conveniently return URLs. Conveniently return CGI Error Codes.
Print in HTML format all name/value pairs input.Print in HTML format Environment variables.The cgi-lib.pl input routines can accept all and process all
methods of input (e.g. GET and POST methods). You do not have to worry about which mechanism has been adopted.
04/12/2023
102
A Sample Form Response CGI Perl Script
In this subsection we will develop a minimal.pl CGI routine that accepts input form our minimal form and sends back HTML that echoes the input data.
We will use the cgi-lib.pl to Parse the input from the form. Format the HTML output.
We will need to learn some more basic Perl: How to include and call Perl libraries. How to call Perl subroutines
The first thing our Perl script will need to do is to include the Perl library file cgi-lib.pl.
The Perl command require will load in any external Perl file. It is easier and sometimes essential that all library files exist in the same folder or directory as the main Perl script calling the library.
Therefore make sure that all Perl files required for a Perl program do exist at the same folder or directory level.
04/12/2023
103
Cont…
Thus to include our cgi-lib.pl file we need the Perl command: require "cgi-lib.pl";
Having included the library we can call on its many useful subroutines.
The &ReadParse() subroutine reads either GET or POST input and conveniently stores the name/value pairs in a Perl array.
Thus a Perl call of the form: &ReadParse(*input); will store the input in an array input. & is used to indicate a Perl subroutine call.
Next we will need to extract out the relevant value of a given name.
In our current example there is only one input field and we are therefore only interested in the value associated with the myfield name.
To get this value you simply do: $input{'myfield'} Thus to print out the value typed we could do something like: print "You typed: " . $input{'myfield'} . "\n";
http://stein.cshl.org/WWW/CGI/cgi-lib_porting.html
04/12/2023
104
A first minimal Perl script
minimalExample.html
<html> <head><title>Sample Example</title></head> <body bgcolor="white"><form method="post" action="/cgi-bin/minimal.cgi"> Please enter your name:<br> <input type="text" name="myfield" size="35"><br> <input type="submit" value="Send"> <input type="reset" value="Reset"> </form> </body> </html>
Minimal.cgi
#!C:\Perl\bin\perl# This is the minimalist form script # to demonstrate the use of # the cgi-lib.pl library
require "cgi-lib.pl";
# Read in all the variables set by the form&ReadParse(*input);print "Content-Type: text/html\n\n";print "<html> <head>\n";print "<title>Sample Input</title>\n";print "</head>\n";print "<body>\n";print "You typed: " . $input{'myfield'} . "\n";print "</body> </html>\n";
04/12/2023
105
A second minimal Perl script
some more cgi-lib.pl subroutines: Nearly every CGI output has:
exactly the same header output. similar HTML head information similar HTML ending
Fortunately subroutines exist to save us typing this same information all the time.
The &PrintHeader subroutine returns the string: Content-Type: text/html\n\n
Thus we can use print in conjunction to produce our CGI header output via: print &PrintHeader;
04/12/2023
106
Cont..
The &HtmlTop subroutine accepts a single string argument, MY TITLE say, and return an HTML Head and Body (opening only) with the argument as the HTML page TITLE and H1 Header. I.e. <html> <head> <title>MY TITLE</title> </head> <body> <h1>MY TITLE</h1>
which is rather useful.The &HtmlBot subroutine is the compliment
of &HtmlTop and returns: </body> </html>
04/12/2023
107
Cont…
Thus we can use these functions and we only need to provide the main HTML body ourselves.
Thus we develop a better minimal.cgi program as follows #!C:\Perl\bin\perl # minimal.cgi # This is the minimalist form script # to demonstrate the use of # the cgi-lib.pl library
require "cgi-lib.pl";
# Read in all the variables set by the form &ReadParse(*input);
# Print the header + html top print &PrintHeader; print &HtmlTop ("Minimal Input"); print "You typed: " . $input{'myfield'} . "\n";
print &HtmlBot;
04/12/2023
108
Installing and Using MySQL
In order to successfully connect to a MySQL database with Perl, you will first need to ensure that the MySQL drivers are installed on your system.
DBI (DataBase Interface) and DBD:MySQL (DataBase Driver for MySQL).
First, we need to start the Perl Package Manager. Click on your start menu and select the Run...option. In the pop-up window, type cmd and hit enter.
This will bring up the Windows command line. If you did the default install of ActiveState's ActivePerl, you
should be able to type ppm at the prompt to start the Perl Package Manager.
First comes the DBI (DataBase Interface) which can be installed by typing install DBI.
Finally we install the MySQL driver for the DBI. This is done by typing install DBD-mysql.
04/12/2023
109
Cont…
When you are able to do some basic administration tasks, let's create a database called mydb in mysql.
And in that database, we will create a simple table called ofuser and populate it with some data.
Here is the SQL you'll need to create the table and fill in a few records, just connect to your MySQL database and run them.
CREATE DATABASE mydb; USE mydb; CREATE TABLE ofuser ( id int(10) unsigned NOT NULL
auto_increment, name varchar(128) NOT NULL default '', phone varchar(128) NOT NULL default '', PRIMARY KEY (id) );
INSERT INTO ofuser VALUES (1, 'Some Person', '555'); INSERT INTO ofuser VALUES (2, 'Another Person', '222');
04/12/2023
110
Cont…
Now that we have a database to connect to, let's look at how we access the information from our Perl programs. The following is a simple script that connects to the database and runs a short bit of SQL to retrieve all the samples. #!C:\Perl\bin\perl.exe use strict; use CGI::Carp qw(fatalsToBrowser); use CGI qw(:standard); use DBI; my $dbh; my $user = "root"; my $password = "admin"; print header, start_html; $dbh = DBI->connect("dbi:mysql:database=mydb;host=localhost:3306;", $user, $password); my $sth = $dbh->prepare('select * from ofuser'); $sth->execute; print "<ul>"; while (my @row = $sth->fetchrow_array) { print "<li>@row\t"; } print "</ul>"; print end_html;
The first thing we need to do is let the Perl interpreter know that we intend to use the Perl DBI function library, by including it in our program with the use function.
Next we'll need to create a connection to the database itself. For this part of the script, your mydb database will need to be running.
Finally we use the fetchrow_array function to fetch each row of the results from the MySQL database and print them one to a line.
04/12/2023
111
Exercise
Create an html login form, try to authenticate it via mysql database and if authentication is valid then it should go to welcome page displaying your user name and your details.
04/12/2023
112
Using Cookies in CGI
HTTP protocol is a stateless protocol. But for a commercial website it is required to
maintain session information among different pages.
For example one user registration ends after completing many pages.
But how to maintain user's session information across all the web pages.
04/12/2023
113
Cont…
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
04/12/2023
114
Cont…
How It Works Your server sends some data to the visitor's
browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the
visitor's hard drive. Now, when the visitor arrives at another page on
your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what
was stored.
04/12/2023
115
Cont…
Cookies are a plain text data record of 5 variable-length fields: Expires : The date the cookie will expire. If this is blank, the
cookie will expire when the visitor quits the browser. Domain : The domain name of your site. Path : The path to the directory or web page that set the
cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value : Cookies are set and retrviewed in the form of key and value pairs.
04/12/2023
116
Example
Setting up Cookies This is very easy to send cookies to browser. These cookies will be
sent along with HTTP Header. Assuming you want to set UserID and Password as cookies. So it will be done as follows: #!C:\Perl\bin\perl.exe use strict; use CGI qw(:standard); use CGI::Carp qw(warningsToBrowser fatalsToBrowser); print "Set-Cookie:UserID=XYZ;\n"; print "Set-Cookie:Password=XYZ123;\n"; print "Set-Cookie:Expires=Tuesday, 25-Dec-2012 23:12:40 GMT \n"; print "Content-type:text/html\r\n\r\n";
From this example you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.
#!C:\Perl\bin\perl.exeuse strict;use CGI qw/:standard/;use CGI::Carp qw(warningsToBrowser fatalsToBrowser);my $cookie = cookie(
-name=>'CGI-PERL-COOKIE-EXAMPLE',
value=>'cookie.linuxconfig.org',-expires=>'+1y');
print header (-cookie=>$cookie),
start_html('CGI Cookie with Exipire Date'),p("Cookie had been saved !\n"),
end_html;exit;
The following code uses same principles of creating a cookies however on larger scale. When creating a cookies we need to keep in mind that there is a limitation of maximum 20 cookies per domain. Use a following code to create multiple cookies simultaneously. The code first creates a scalar variable to hold a cookies definitions and then we print a header with both cookies in form of array.
#!C:\Perl\bin\perl.exeuse strict;use CGI qw/:standard/;my $cookie1 = cookie(-name=>'cookie_one',value=>'value1',expires=>'+1d');my $cookie2 = cookie(-name=>'cookie_two',value=>'value2',expires=>'+10y');print header (-cookie=>[$cookie1,$cookie2]),start_html('CGI Multiple Cookie Example'),p("Cookies received!\n"),end_html;exit;
04/12/2023
117
Retrieving Cookies
This is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form.
key1=value1;key2=value2;key3=value3....
Here is an example of how to retrieving cookies. #!C:\Perl\bin\perl.exe use strict; use CGI qw(:standard); use CGI::Carp qw(warningsToBrowser fatalsToBrowser); my $cookie;my $key;my $val;my $user_id;my $password; print "Content-type:text/html\r\n\r\n"; my $rcvd_cookies = $ENV{'HTTP_COOKIE'}; my @cookies = split /;/, $rcvd_cookies; foreach $cookie ( @cookies ){ ($key, $val) = split(/=/, $cookie); # splits on the first =. $key =~ s/^\s+//; $val =~ s/^\s+//; $key =~ s/\s+$//; $val =~ s/\s+$//; if( $key eq "UserID" ){ $user_id = $val; }elsif($key eq "Password"){ $password = $val; } } print "User ID = $user_id\n"; print "Password = $password\n";
#!C:\Perl\bin\perl.exeuse strict;use CGI qw/:standard/;use CGI::Carp qw(warningsToBrowser fatalsToBrowser);my $retrieve_cookie = cookie('CGI-PERL-COOKIE-EXAMPLE');
print header,start_html,p("Cookie value is $retrieve_cookie\n"),end_html;exit;
Similarly the code below retrieves multiple cookies at once:#!C:\Perl\bin\perl.exeuse strict;
use CGI qw/:standard/;my $retrieve_cookie1 = cookie('cookie_one');
my $retrieve_cookie2 = cookie('cookie_two');print header,start_html,p("COOKIE_ONE Value: $retrieve_cookie1 \n"),
p("COOKIE_TWO Value: $retrieve_cookie2 \n"),end_html;exit;
04/12/2023
118
What is sendmail?
Sendmail is the most popular Unix-based implementation of the Simple Mail Transfer Protocol (SMTP) for transmitting e-mail.
When a sendmail server receives e-mail, it attempts to deliver the mail to the intended recipient.
However, because it does not provide a mailbox facility and for other reasons, other software such as a POP3 or Internet Message Access Protocol server are also needed.
Most Internet service providers (ISPs) provide both an SMTP server (such as sendmail) and a POP or IMAP server.
04/12/2023
119
How does sendmail for windows work?
In perl or php or asp scripts we can write a code to send mail to mail recepients.
We direct data to program sendmail.exe who sends email to person or persons that our script sends.
So all we need is to send header and email-msg to sendmail.exe program and that is it.
04/12/2023
120
Installation of sendmail.exe
All of scripts are in cgi-bin folder (for example c:\Inetpub\wwwroot\testdomain.com\httpdocs\cgi-bin\). "Cgi-bin" folder must have execute permissions.
04/12/2023
121
Cont…
Download sendmail.zip http://velikan.net/sendmail-for-windows-iis/sendmail.zip
Now upload sendmail.zip to your cgi-bin folder end extract contents.
Next step is to edit sendmail.ini file. You only need to set your domain and if you do not have your own smtp server installed on your server you can write smtp mail server of your internet service provider.
04/12/2023
122
Cont…
That is it. You have successfully installed sendmail.exe program for windows - now only thing for you is to use it...
04/12/2023
123
Example
#!C:\Perl\bin\perl.exe
use CGI qw(:standard); use CGI::Carp qw(warningsToBrowser fatalsToBrowser); use strict; print "Content-type: text/html\n\n"; my $title='Perl Mail demo'; my $to='[email protected]'; my $from= '[email protected]'; my $subject='YOUR SUBJECT'; open(MAIL, "|sendmail/sendmail.exe -t");
## Mail Header
print MAIL "To: $to\n"; print MAIL "From: $from\n"; print MAIL "Subject: $subject\n\n";
## Mail Body
print MAIL "This is a test message from CGI-Perl! You can write your mail body text here\n"; close(MAIL); print "<html><head><title>$title</title> </head>\n<body>\n\n";
## HTML content let use know we sent an email
print "<h1>$title</h1>\n"; print "<p>A message has been sent from $from to $to"; print "\n\n</body></html>";
04/12/2023
124
In UNIX
#!/usr/bin/perl print "Content-type: text/html\n\n"; $title='Perl Mail demo'; $to='MAIL ADDRESS TO SEND TO'; $from= '[email protected]'; $subject='YOUR SUBJECT'; open(MAIL, "|/usr/sbin/sendmail -t");
## Mail Header print MAIL "To: $to\n"; print MAIL "From: $from\n"; print MAIL "Subject: $subject\n\n";
## Mail Body print MAIL "This is a test message ! You can write your mail body text here\
n"; close(MAIL); print "<html><head><title>$title</title> </head>\n<body>\n\n";
## HTML content let use know we sent an email print "<h1>$title</h1>\n"; print "<p>A message has been sent from $from to $to"; print "\n\n</body></html>";
04/12/2023
125
References
http://www.bin-co.com/perl/tutorial/http://www.cs.cf.ac.uk/Dave/PERL/perl_caller.ht
mlhttp://www.java2s.com/Code/Perl/CGI/CatalogC
GI.htmhttp://cgi-app.org/index.cgi?Exampleshttp://perldoc.perl.org/5.14.0/CGI.htmlhttp://perl.about.com/od/perltutorials/a/perlmys
ql.htmhttp://www.perl.com/pub/2003/10/23/databases
.htmlhttp://anzer.tripod.com/uwindows.htm