CGI with Perl Darby Tien-Hao Chang (a.k.a. dirty) Department of Electrical Engineering, National Cheng Kung University.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

Lecture 6/2/12. Forms and PHP The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input When dealing with HTML forms.
CGI Programming.
JavaScript Forms Form Validation Cookies. What JavaScript can do  Control document appearance and content  Control the browser  Interact with user.
CGI Programming Part 2. Input Tags Many different ways of getting data from the user. The tag is used most often. has a type attribute –Specifies the.
JavaScript Forms Form Validation Cookies CGI Programs.
Tutorial 6 Working with Web Forms
Python and Web Programming
Guide To UNIX Using Linux Third Edition
Tutorial 6 Working with Web Forms. XP Objectives Explore how Web forms interact with Web servers Create form elements Create field sets and legends Create.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Chapter 9 Collecting Data with Forms. A form on a web page consists of form objects such as text boxes or radio buttons into which users type information.
1 ‘Dynamic’ Web Pages So far, we have developed ‘static’ web-pages, e.g., cv.html, repair.html and order.html. There is often a requirement to produce.
Chapter 9 Using Perl for CGI Programming. Computation is required to support sophisticated web applications Computation can be done by the server or the.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Web forms in PHP Forms Recap  Way of allowing user interaction  Allows users to input data that can then be processed by a program / stored in a back-end.
Application Development Description and exemplification of server-side scripting language for server connection, database selection, execution of SQL queries.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
Forms and Form Controls Chapter What is a Form?
Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1.
1 HTML and CGI Scripting CSC8304 – Computing Environments for Bioinformatics - Lecture 10.
Comp2513 Forms and CGI Server Applications Daniel L. Silver, Ph.D.
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
JavaScript, Fourth Edition
Robinson_CIS_285_2005 HTML FORMS CIS 285 Winter_2005 Instructor: Mary Robinson.
2 1 Sending Data Using a Hyperlink CGI/Perl Programming By Diane Zak.
Python CGI programming
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 6.
PHP meets MySQL.
USING PERL FOR CGI PROGRAMMING
CSC 2720 Building Web Applications HTML Forms. Introduction  HTML forms are used to collect user input.  The collected input is typically sent to a.
Chapter 8 Cookies And Security JavaScript, Third Edition.
CIS 451: ASP.NET Objects Dr. Ralph D. Westfall January, 2009.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
Website Development with PHP and MySQL Saving Data.
Chapter 9: Perl and CGI Programming CGI Programming Acknowledgement: Some materials are taken from Teach Yourself CGI Programming with PERL 5 in a Week.
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
1 © Netskills Quality Internet Training, University of Newcastle HTML Forms © Netskills, Quality Internet Training, University of Newcastle Netskills is.
11 1 Cookies CGI/Perl Programming By Diane Zak Objectives In this chapter, you will: Learn the difference between temporary and persistent cookies.
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
HTML FORMS GET/POST METHODS. HTML FORMS HTML Forms HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes,
XHTML & Forms. PHP and the WWW PHP and HTML forms – Forms are the main way users can interact with your PHP scrip Typical usage of the form tag in HTML.
Tutorial 6 Working with Web Forms. XP Objectives Explore how Web forms interact with Web servers Create form elements Create field sets and legends Create.
3 1 Sending Data Using an Online Form CGI/Perl Programming By Diane Zak.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
1 HTML Forms
Introduction to Programming the WWW I CMSC Winter 2003.
Netprog 2002 CGI Programming1 CGI Programming CLIENT HTTP SERVER CGI Program http request http response setenv(), dup(), fork(), exec(),...
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Tutorial 6 Working with Web Forms. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Explore how Web forms interact with.
Netprog CGI and Forms1 CGI and Forms A detailed look at HTML forms.
1 State and Session Management HTTP is a stateless protocol – it has no memory of prior connections and cannot distinguish one request from another. The.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
PHP Form Processing * referenced from
1 HTML forms (cont.)
Introduction to CGI PROG. CGI stands for Common Gateway Interface. CGI is a standard programming interface to Web servers that gives us a way to make.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
Lesson 5 Introduction to HTML Forms. Lesson 5 Forms A form is an area that can contain form elements. Form elements are elements that allow the user to.
Unit 4 Working with data. Form Element HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes, radio-buttons,
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
University of Kansas Department of Electrical Engineering and Computer Science Dr. Susan Gauch April 21, 2005 I T T C Introduction to Web Technologies.
2440: 141 Web Site Administration Web Forms Instructor: Joseph Nattey.
PHP-II.
Presentation transcript:

CGI with Perl Darby Tien-Hao Chang (a.k.a. dirty) Department of Electrical Engineering, National Cheng Kung University

A typical Perl CGI session goes something like this:

hello.pl #!/usr/bin/perl print "Content-type: text/html\r\n\r\n"; print " \n"; print " Hello World! \n"; print " \n"; print " Hello World! \n"; print " \n"; exit (0);

Anatomy of a CGI program A CGI program always has 3 basic parts:  MIME type  HTML document  Return value

MIME type Content-type: text/html The "\r\n\r\n" is required by the MIME standards (it stands for CRLF CRLF, for those that are curious) text/plain Plain text, not processed as HTML by the browser text/tab-separated-values Data that will be loaded into a spreadsheet-like program image/jpeg, image/png The data will be displayed as an image application/pdf The document should be viewed by a PDF reader

HTML document You know that

Return value After a CGI program ends, the web server collects the "return value" of the program so that it knows if there was an error or not This is sometimes useful for debugging purposes because the programmer is allowed to determine the meaning of non-zero return values In Perl, you can specify what the return value of the CGI program is with the exit keyword:  exit (0); # normal exit code  exit (1): # something bad happened Change the return value in your hello.pl to a '1' and see if you can find the resulting error code in your web server's error log.

Let ’ s see the log of your httpd

hello.pl with CGI.pm #!/usr/bin/perl # It's always a good idea to use the strict pragma while developing # Perl code, it makes Perl warn about dangerous code use strict; # We're also going to include the CGI module, so that we can take # advantage of other programmer's efforts (One of Larry Wall's basic # tennants is that programmers are fundamentally lazy -- he's probably # right, but I can't be bothered to prove it right now) use CGI; # instantiate a new CGI object my $cgi = new CGI; # perform a single print statement, with liberal use of the perl # string concatenator "." and some CGI methods print  $cgi->header. $cgi->start_html('Hello World!').  $cgi->h1('Hello World!'). $cgi->end_html; # Tell the webserver everything is fine exit (0);

Where is my CGI.pm? Hey, TA

About HTML forms An HTML tag is the foundation of a user input section on a web page.  Everything following that tag through the corresponding tag can contain elements such as these:  A Text Input Box   A Radio Button   A Check Box   A Hidden Varible   A Submit Button  Where each element has a name and an associated value. The value may be included with the tag itself (see the radio and hidden examples above), and/or it can be supplied by the user.

Names Variable names can be any legal HTML identifier and are almost always supplied via the name property of an HTML tag:  Once the form above is sent to the web server, the CGI program will be able to access these elements by those names:  my $foo = $cgi->param('foo');  my $bar = $cgi->param('bar');  my $hair_index = $cgi->param('Desired Hair Color');  my $date = new Date($cgi->param('Date'));  my $name = $cgi->param('First Name');

Values A value can either be a string (as shown above), or it can be an array of items How do you access the variables in the case that you have a series of checkboxes?  = $cgi->param('listOfStuff');

POST and GET Let's take a closer look at the tag:  The action attribute is a path to your CGI program, but what does the method attribute do? There are two different ways that an HTTP request can send CGI variables to a server, GET and POST

GET A GET request is encoded in the URL of an HTTP request by using the question-mark (?) delimiter:  Everything after the question mark is the query in the format of name=value A typical CGI program for the above request:  my $first_name = $cgi->param('fname');  my $last_name = $cgi->param('lname');  print "$first_name $last_name"; And the result will be:  Craig Kelley You can see the variables and their values in the location bar of most web browsers You should always keep GET requests under 1024 characters, otherwise you may run into problems with older browsers

POST A POST request is sent along what is known as an out-of-band (OOB) channel that does not utilize the URL, but rather a special network pipe of its own The advantage of this method over the GET method is that a lot of data can be sent without cluttering up the URL A POST request will look like any other request:  But the browser will tell the web server that it has additional variable information, and it will be sent along the same connection that the URL is sent Many web applications that deal in a lot of data are well served with POST sessions

Which to Use? It is good practice to use the GET method whenever you are able to because the POST method is more difficult for a user to manage, and it doesn't function well with a browser's back or history button On the other side, it's a good idea to use the POST method when something secure or private is being sent such as a password or a credit card number

Sample HTML and CGI program

Using cookies What is a Cookie?  A cookie is a text-only string that gets entered into the memory of your browser  This value of a variable that a website sets  If the lifetime of this value is set to be longer than the time you spend at that site, then this string is saved to file for future reference Why do sites use Cookies  These range from the ability to personalize information (like on My Yahoo or Excite), or to help with on-line sales/services (like on Amazon Books or eBay), or simply for the purposes of collecting demographic information (like DoubleClick)  Cookies also provide programmers with a quick and convenient means of keeping site content fresh and relevant to the user's interests  The newest servers use cookies to help with back-end interaction as well, which can improve the utility of a site by being able to securely store any personal data that the user has shared with a site (to help with quick logins on your favorite sites, for example)

Let ’ s see how many cookies in your browser

Using cookies Set cookies  $cgi->header( -cookie => new CGI::Cookie(  -name => 'Monster',  -value => $cgi->param('Monster'),  -expires => '+3d',  -domain => 'inconnu.isu.edu‘ )  ) Get cookies  $cgi->cookie('Monster')

Database CGI # setup database connection variables my $user = "some username goes here"; my $password = "some password goes here"; my $host = "the host you want to connect to"; my $driver = "mysql"; # connect to database my $dsn = "DBI:$driver:database=cis430;host=$host"; my $dbh = DBI->connect($dsn, $user, $password);

Some notes about the program There is no HTML file for this program All of the necessary document data is contained within the CGI program, and a default page is displayed when there is no form data to show directly from the program Results are shown only when the submit button was pressed  if ($cgi->param('Query')) | Field | Type | | filename | varchar(255) | | artist | varchar(64) | | song | varchar(64) | | album | varchar(64) | | track | int(11) |

Basic Perl syntax guide - variables: scalars, arrays, hashes The scalar can hold one specific piece of information at a time, such as a string, integer, or reference All variables, whether they be a scalar, array, hash, or other type, are CASE-SENSITIVE, meaning that $myvar and $MYVAR are treated as two different variables

Variable scope Whenever you first define either a scalar, array, or hash, use the my keyword to denote that it belongs to a particular scope Scope is a particular area inside opening and closing brackets, and defines where a variable is accessible from  my $string = ‘David’;  { $string = ‘John’;  }  print $string; # this will print the text “John”

Variable scope  my $string = ‘David’;  { my $string = ‘John’;  }  print $string;  $string = ‘David’;  print $string;  { my $string = ‘John’;  }  print $string;

Single/double quote my $text = ‘cool guy’; my $string = ‘some $text’; print $string; # prints literally “some $text”; my $text = ‘cool guy’; my $string = “some $text”; print $string; # prints literally “some cool guy”; my $ = # fine – no error my $ = # an error message my $ = # fine – no error

Array Arrays are simply a list of scalar variables Arrays begin with sign instead of a dollar ($) sign  = (“string 1”, “string 2”, “string 3”); To access an array  foreach my $value  { print $value. “\n”;  }  print $array[0]. “\n”;  print $array[1]. “\n”;  print $array[2]. “\n”; So when you’re referencing an individual element of an array, you use a dollar sign, not sign

Hash A hash is a list of name value pairs To define a hash, use this syntax (the percent sign):  my %hash; To add new values to a hash, use this syntax:  $hash{‘key1’} = ‘value1’;  $hash{‘key2} = ‘value2’;  $hash{‘key3’} = ‘value3’; To access hash elements, simply reference the hash key name:  print $hash{‘key1’}; # prints “value1” To loop through all elements in a hash:  while (my($key, $value) = each(%hash))  { print $key. ‘ – ‘. $value. “\n”;  }  foreach my $key (keys(%hash)) { print $key, “ – “, $hash{$key}, “\n”;  }

Accessing the file system with Perl Create an empty file:  open(FILEHANDLE, “>/path/to/my/file.txt”) || die(‘cannot open file: ‘. $!);  close(FILEHANDLE); A greater than sign “>” means open in write mode, erasing any previous contents of the file Two greater than signs “>>” mean open in append mode, meaning add our new data to the file after the data that already existed You can almost always get the path to your document root (where your web server serves its initial index.html file from) by using this syntax:  my $document_root = $ENV{‘DOCUMENT_ROOT’}; The die function prints an error message if what we tried to do didn’t succeed The $! Variable is a special perl variable which contains the last error the perl program had before it exited Writing data to a file (in write mode – existing data in file is erased):  print FILEHANDLE ‘some data is now in this file, and if any data was already in the file, it is now gone.’;  close(FILEHANDLE);

Reading data from a file open(FILEHANDLE, “/path/to/my/file.txt”) || die(‘cannot open file: ‘. $!); # this will only print the first line of the file: print $_; # this will print all lines of data in the file: while( ) {  print $_; } close(FILEHANDLE);

Exercise Counter  With cookies  With a text file  With MySQL

Remember our wonderful program? A step-by-step wrapping/deployment procedure

A program without input (parameter) Write your program Compile it Write a CGI program Call your program from the CGI program Parse the output of your program and then generate a HTML view Make sure other users could access your CGI program from browser

A program with input (parameters) Write your program Compile it Write a HTML to provide users a interface for input Write a CGI program to receive user input Call your program from the CGI program with user input Parse the output of your program and then generate a HTML view Make sure other users could access your CGI program from browser

Now, what CGI is? A interface We use Perl to implement this interface Two sides of this interface, HTML and your program, don’t care about CGI too much HTML-CGI program  Very simple! CGI program-your program  Depends on yourself

Exercise Choose one program and give it a web dressing