cgi with perl darby tien-hao chang (a.k.a. dirty) department of electrical engineering, national...

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

Upload: pearl-moore

Post on 27-Dec-2015

218 views

Category:

Documents


2 download

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 "<HTML>\n"; print "<HEAD><TITLE>Hello World!</TITLE></HEAD>\n"; print "<BODY>\n"; print "<H2>Hello World!</H2>\n"; print "</BODY>\n"; print "</HTML>\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<CRLF><CRLF> The "\r\n\r\n" is required by the MIME standards (it st

ands 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 <form> tag is the foundation of a user input section on a web page. <form method="get" action="/cgi-bin/myscript.pl">

Everything following that tag through the corresponding </form> tag can contain elements such as these: A Text Input Box <input type="text" name="foo"> A Radio Button <input type="radio" name="color" value="blue> A Check Box <input type="chekcbox" name="isMarried"> A Hidden Varible <input type="hidden" name="StateVariable" value="1"> A Submit Button <input type="submit" name="StateVariable">

Where each element has a name and an associated value. The value may be included with the tag itself (see the radio and hidden example

s 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: <input name="foo" ... > <input name="bar" ... > <input name="Desired Hair Color" ... > <input name="Date" ... > <input name="First Name" ... >

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? my @values = $cgi->param('listOfStuff');

POST and GET

Let's take a closer look at the <form> tag: <form method="post" action="/cgi-bin/myscript.p

l"> The action attribute is a path to your CGI pro

gram, but what does the method attribute do? There are two different ways that an HTTP re

quest 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: http://somserver/cgi-bin/foo.pl?fname=Craig&lname=Kelley

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: http://someserver/cgi-bin/my_script.pl

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 http://dirty.csie.org/form_example.html http://dirty.csie.org/lesson2.pl

Using cookies

What is a Cookie? A cookie is a text-only string that gets entered into the memory of your brows

er 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 p

rogram, 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 info

rmation 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 $email = ‘[email protected]’;  # fine – no error my $email = “[email protected]”; # an error message my $email = “david\@somehost.net”; # fine – no error

Array

Arrays are simply a list of scalar variables Arrays begin with an @ sign instead of a dollar ($) sign

my @array = (“string 1”, “string 2”, “string 3”); To access an array

foreach my $value (@array) {

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 the @ 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 pr

ogram 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(<FILEHANDLE>) {

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 in

put Parse the output of your program and then generate

a HTML view Make sure other users could access your CGI progr

am 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