Cgi

111,504 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
111,504
On SlideShare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
133
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Cgi

  1. 1. G I R I S H S R I V A S T A V A 7/5/2013 1
  2. 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 7/5/2013 2
  3. 3. Cont…  Introduction to Perl  The CGI.pm Module  Pattern Matching  Arrays  Dealing With Files In PERL  Basic HTML  What is cgi-lib.pl?  Communicating with databases  Sending mail with Perl – CGI Scripts 7/5/2013 3
  4. 4. Dynamic Web 7/5/2013 4  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.
  5. 5. Cont… 7/5/2013 5
  6. 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. 7/5/2013 6
  7. 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. 7/5/2013 7
  8. 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. 7/5/2013 8
  9. 9. Some Things to Remember About CGI 7/5/2013 9  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.
  10. 10. Uses of CGI Scripts 7/5/2013 10  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.
  11. 11. Why Use CGI? 7/5/2013 11  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.
  12. 12. Why Not Use CGI? 7/5/2013 12  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.
  13. 13. Comparing Server-Side Web Languages 7/5/2013 13  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.
  14. 14. Java Scripts And Other Web Technologies… 7/5/2013 14  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).
  15. 15. Cont… 7/5/2013 15  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.
  16. 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. 7/5/2013 16
  17. 17. CGI Architecture Diagram 7/5/2013 17
  18. 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 7/5/2013 18
  19. 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. 7/5/2013 19
  20. 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. 7/5/2013 20
  21. 21. History of Perl  Perl was introduced in 1987  reason 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.
  22. 22. 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.
  23. 23.  written by Larry Wall  A GNU product FREE, Open Source software  Interpreted and not compiled!  Originally designed for UNIX®, but is portable to other O/S  stable, cross platform programming language Introduction
  24. 24. What does Perl stand for?  „Perl‟ isn‟t really an acronym  2 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
  25. 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." 7/5/2013 25
  26. 26. 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.
  27. 27. Cont… Perl Features  supports Unicode.  supports both procedural and OO programming.  extensible.  The Perl interpreter can be embedded into other systems.
  28. 28. 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.
  29. 29. 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.
  30. 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 7/5/2013 30
  31. 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.cgi  Scroll down to locate Win32 Binary without crypto (no mod_ssl) (MSI Installer). http://www.webdevelopersnotes.com/how-do-i/install-apache-windows-7.php 7/5/2013 31
  32. 32. First CGI Program  #!C:Perlbinperl.exe  use CGI;  print "Content-Type: text/htmlnn";  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"; 7/5/2013 32
  33. 33. Explanation  The first line of your program should look like this:  #!C:Perlbinperl -wT  The first part of this line, #!, indicates that this is a script. The next part, C:Perlbinperl.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/htmlnn";  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. 7/5/2013 33
  34. 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 . . . 7/5/2013 34
  35. 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 . . . ###################################### 7/5/2013 35
  36. 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(){ …} 7/5/2013 36
  37. 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 7/5/2013 37
  38. 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‟. 7/5/2013 38
  39. 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‟ 7/5/2013 39
  40. 40. Example  #!C:Perlbinperl.exe  my $text = 'cool guy';  my $string = "some $text";  print $string; # prints literally “some cool guy”; Arrays #!C:Perlbinperl -w #DEFINE SOME ARRAYS @days = ("Monday", "Tuesday", "Wednesday"); @months = ("April", "May", "June"); #PRINT MY ARRAYS TO THE BROWSER print @days; print @months; Hashes #!C:Perlbinperl -w #DEFINE SOME HASHES %hashName = ('key1', 'value1', 'key2', 'value2'); %ourFriends = ('best', 'Don', 'good', 'Robert', 'worst', 'Joe'); #PRINT MY HASHES TO THE BROWSER print $hashName{'key1'}; print $ourFriends{'good'}; 7/5/2013 40
  41. 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. 7/5/2013 41 #!C:Perlbinperl.exe $one = 1; $two = 2; $three = 3; $four = 4; $abcd = "abcd"; $pqrs = "pqrs"; $xyz = "xyz"; # concantenate the two strings and print print $abcd . " another stringn"; # repeat the string abcd three times print $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 two print $three ** $two . "n"; # exponentiation - three raised to power two print $one++ . "n"; # post increment print ++$one . "n"; # pre increment print $one-- . "n"; # post decrement print --$one . "n"; # pre decrement $one += $two; # $one = $one + $two $one -= $two; # $one = $one - $two
  42. 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"; } 7/5/2013 42 #!C:Perlbinperl.exe my $number = 95; if($number eq 92) { print 'Number is ninety-five!'; } else { print 'Number is not ninety-five'; }
  43. 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  } 7/5/2013 43
  44. 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. 7/5/2013 44
  45. 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  } 7/5/2013 45 #!C:Perlbinperl.exe @array = ("value1", "value2", 1, 2, 3, 4); foreach my $value (@array) { print $value; } #!C:Perlbinperl.exe $integer = 0; while($integer < 50) { print $integer; $integer++; } Until #!C:Perlbinperl.exe $firstVar = 10; until ($firstVar > 12) { print("inside: firstVar = $firstVarn"); $firstVar++; } print("outside: firstVar = $firstVarn"); This program displays: inside: firstVar = 10 inside: firstVar = 11 inside: firstVar = 12 outside: firstVar = 13
  46. 46. Exercise 7/5/2013 46 1. Create a program using PERL, which gives the output as per the following figure: * * * * * * * * * * * * * * *
  47. 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 "$in";  }  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 "$in"; }  This example prints the numbers from 1 to 12, then terminates the loop when it reaches 13. 7/5/2013 47
  48. 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. 7/5/2013 48
  49. 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. 7/5/2013 49
  50. 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:Perlbinperl.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) 7/5/2013 50
  51. 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; 7/5/2013 51
  52. 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> 7/5/2013 52
  53. 53. Cont…  The end_html function prints out the closing HTML tags:  </body>  </html>  #!C:Perlbinperl.exe  use CGI qw(:standard);  print header;  print start_html("Hello World");  print "<h2>Hello, world!</h2>n";  print end_html; 7/5/2013 53
  54. 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 7/5/2013 54
  55. 55. HTML Document <html> <head><title>Test Page</title></head> <body> <b>Hello, world</b> </body> </html> Document Structure - Head - Body 7/5/2013 55
  56. 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> 7/5/2013 56
  57. 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 7/5/2013 57
  58. 58. HTML Tags (continued) The affected text is contained within the tags  <B>Hello</B> ------- Hello  <I>Bye!</I> ---------- Bye  Ordered list <OL> <LI>Apple</LI> <LI>Banana</LI> <LI>Orange</LI> </OL> 1. Apple 2. Banana 3. Orange 7/5/2013 58
  59. 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 7/5/2013 59
  60. 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> 7/5/2013 60
  61. 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 text  action specifies the address of the script that is going to process the current form data 7/5/2013 61
  62. 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 7/5/2013 62
  63. 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”> 7/5/2013 63
  64. 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) 7/5/2013 64
  65. 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"; } } 7/5/2013 65
  66. 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> 7/5/2013 66
  67. 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";  } 7/5/2013 67
  68. 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"; 7/5/2013 68
  69. 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": 7/5/2013 69
  70. 70. Cont… 7/5/2013 70
  71. 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. 7/5/2013 71
  72. 72. Exercise 7/5/2013 72
  73. 73. Exercise 7/5/2013 73  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.
  74. 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. 7/5/2013 74
  75. 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 successn";  } else {  print "Did not find successn"; } 7/5/2013 75
  76. 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. 7/5/2013 76
  77. 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 Characters  Some 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. 7/5/2013 77
  78. 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". 7/5/2013 78
  79. 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. 7/5/2013 79
  80. 80. Cont…  Repetition Characters  The 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 7/5/2013 80
  81. 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!". 7/5/2013 81
  82. 82. Process form with regular expression: first name and last name 7/5/2013 82  <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>
  83. 83. Cont… 7/5/2013 83  #!C:Perlbinperl.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 Lu$firstName.</p>";  }  if ( $lastName =~ /^w+$/ ) {  print "<p>Hello there Mr./Ms. Lu$lastName.</p>";  }  print end_html();
  84. 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.7/5/2013 84
  85. 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 "$in";} 7/5/2013 85
  86. 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 Arrays  You 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); 7/5/2013 86
  87. 87. Dealing With HTML Components in perl-cgi 7/5/2013 87  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();
  88. 88. Form Example 7/5/2013 88  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:Perlbinperl use CGI ':standard'; print header(); print "Form Elements", br(), br(), br(); print start_form; print "A Text Box: &nbsp; &nbsp; &nbsp; ", textfield('surname', 'Default', 50), br(); print "A Select Box: &nbsp; &nbsp; &nbsp; ", popup_menu('SelectBox', ['Perl', 'Web', 'Development']); print p, "Text Area: &nbsp; &nbsp; &nbsp;", 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')); }
  89. 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); 7/5/2013 89
  90. 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); 7/5/2013 90
  91. 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); 7/5/2013 91
  92. 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 7/5/2013 92
  93. 93. Reading And Writing Data File (script) #!C:Perlbinperl.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; 7/5/2013 93
  94. 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 7/5/2013 94
  95. 95. Writing Data File #!C:Perlbinperl.exe use CGI; $q=new CGI; print "Content-type: text/htmlnn"; my $name=$q->param("name"); my $outputfile="users.txt"; if (open (OUTPUT, ">>$outputfile")) # open a file { print OUTPUT "$namen"; # write the user name to the file print "<HTML><BODY>Thank you! $name</BODY></HTML>"; } 7/5/2013 95 <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>
  96. 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.txt chmod a+w users.txt 7/5/2013 96
  97. 97. Exercise 7/5/2013 97  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.
  98. 98. Debugging  Default response of the server: "Internal Server Error" --- not useful  Better ways: In the script use CGI::Carp qw(fatalsToBrowser); In the UNIX shell (check the syntax) perl -cw scriptname.cgi 7/5/2013 98 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);
  99. 99. Debugging (continued)  use CGI::Carp qw(fatalsToBrowser); 7/5/2013 99
  100. 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 7/5/2013 100
  101. 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.7/5/2013 101
  102. 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. 7/5/2013 102
  103. 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"; 7/5/2013 103 http://stein.cshl.org/WWW/CGI/cgi-lib_porting.html
  104. 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:Perlbinperl # 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/htmlnn"; 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"; 7/5/2013 104
  105. 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/htmlnn  Thus we can use print in conjunction to produce our CGI header output via:  print &PrintHeader; 7/5/2013 105
  106. 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> 7/5/2013 106
  107. 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:Perlbinperl  # 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; 7/5/2013 107
  108. 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. 7/5/2013 108
  109. 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'); 7/5/2013 109
  110. 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:Perlbinperl.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>@rowt";  }  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. 7/5/2013 110
  111. 111. Exercise 7/5/2013 111  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.
  112. 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. 7/5/2013 112
  113. 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. 7/5/2013 113
  114. 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. 7/5/2013 114
  115. 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. 7/5/2013 115
  116. 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:Perlbinperl.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/htmlrnrn";  From this example you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies. #!C:Perlbinperl.exe use 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:Perlbinperl.exe use 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; 7/5/2013 116
  117. 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:Perlbinperl.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/htmlrnrn";  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_idn";  print "Password = $passwordn"; #!C:Perlbinperl.exe use 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_cookien"), end_html; exit; Similarly the code below retrieves multiple cookies at once: #!C:Perlbinperl.exe use 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; 7/5/2013 117
  118. 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. 7/5/2013 118
  119. 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. 7/5/2013 119
  120. 120. Installation of sendmail.exe  All of scripts are in cgi-bin folder (for example c:Inetpubwwwroottestdomain.comhttpdoc scgi-bin). "Cgi-bin" folder must have execute permissions. 7/5/2013 120
  121. 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. 7/5/2013 121
  122. 122. Cont… That is it. You have successfully installed sendmail.exe program for windows - now only thing for you is to use it... 7/5/2013 122
  123. 123. Example  #!C:Perlbinperl.exe  use CGI qw(:standard);  use CGI::Carp qw(warningsToBrowser fatalsToBrowser);  use strict;  print "Content-type: text/htmlnn";  my $title='Perl Mail demo';  my $to='girish092.ch@gmail.com';  my $from= 'girish092.ch@gmail.com';  my $subject='YOUR SUBJECT';  open(MAIL, "|sendmail/sendmail.exe -t");  ## Mail Header  print MAIL "To: $ton";  print MAIL "From: $fromn";  print MAIL "Subject: $subjectnn";  ## Mail Body  print MAIL "This is a test message from CGI-Perl! You can write your  mail body text heren";  close(MAIL);  print "<html><head><title>$title</title>  </head>n<body>nn";  ## 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 "nn</body></html>"; 7/5/2013 123
  124. 124. In UNIX 7/5/2013 124  #!/usr/bin/perl  print "Content-type: text/htmlnn";  $title='Perl Mail demo';  $to='MAIL ADDRESS TO SEND TO';  $from= 'webmaster@YOURDOMAIN.COM';  $subject='YOUR SUBJECT';  open(MAIL, "|/usr/sbin/sendmail -t");  ## Mail Header  print MAIL "To: $ton";  print MAIL "From: $fromn";  print MAIL "Subject: $subjectnn";  ## Mail Body  print MAIL "This is a test message ! You can write your mail body text heren";  close(MAIL);  print "<html><head><title>$title</title> </head>n<body>nn";  ## 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 "nn</body></html>";
  125. 125. References  http://www.bin-co.com/perl/tutorial/  http://www.cs.cf.ac.uk/Dave/PERL/perl_caller.html  http://www.java2s.com/Code/Perl/CGI/CatalogCGI.h tm  http://cgi-app.org/index.cgi?Examples  http://perldoc.perl.org/5.14.0/CGI.html  http://perl.about.com/od/perltutorials/a/perlmysql.ht m  http://www.perl.com/pub/2003/10/23/databases.ht ml  http://anzer.tripod.com/uwindows.htm 7/5/2013 125
  126. 126. 126 For any queries, mail: training.materials@ymail.com 7/5/2013

×