Perl. Turning on cgi processing in apache Cgi processing cabability is available in the apache...

Preview:

Citation preview

perl

Turning on cgi processing in apache

• Cgi processing cabability is available in the apache server but needs to be turned on by editing config files.

• Cgi processing handles requests to the server that have url:

http://TheUrl/cgi-bin/…

Turning on cgi processing in apache

• Useful link: http://www.ricocheting.com/server/cgi.html

• Activating CGI• Using Notepad (or other text editor) open

E:\Apache2\conf\httpd.conf (also should be start-menu shortcut called "Edit Apache HTTP httpd.conf File") and search for Options Indexes FollowSymLinks (about line 267) when you find it add ExecCGI to the end so it looks like

Options Indexes FollowSymLinks ExecCGI

Turning on cgi processing in apache

• Enabling CGI in any directory [optional]• If you want to use CGI outside ScriptAliased directory (ScriptAlias is

usually the Apache2/cgi-bin/), you will need to uncomment the following line:

#AddHandler cgi-script .cgi • becomes AddHandler cgi-script .cgi .pl .rb• (remove the #) I also added .pl behind .cgi so files with the 'perl'

extension are also treated as cgi files.We’ll later use ruby, too so you might as well add rb extensions to the list.You might also want to comment out:

ScriptAlias /cgi-bin/ "E:/Apache2/cgi-bin/" • so it becomes #ScriptAlias /cgi-bin/ "E:/Apache2/cgi-bin/"

Another useful page

• http://www.thesitewizard.com/archive/addcgitoapache.shtml• There are just a few changes to make:• To find perl scripts in cgi-bin directory (fix path, too):• ScriptAlias /cgi-bin/ "C:/Program Files/Apache

Group/Apache/cgi-bin/" • To allow both pl and cgi suffix:• AddHandler cgi-script .cgi .pl .rb• <Directory />

  Options FollowSymLinks  AllowOverride None</Directory>

• Change options to:• Options FollowSymLinks +ExecCGI

On my apache version: about line 187 of the httpdconf file

<Directory />

Options FollowSymLinks ExecCGI Includes

AllowOverride None

Order deny,allow

Deny from all

</Directory>

Turn on cgi• Enabling SSI [optional]• Find the line from Step 1: Activating CGI and add Includes to the end so it becomes Options

Indexes FollowSymLinks ExecCGI Includes

Find and uncomment the following lines #AddType text/html .shtml and #AddOutputFilter INCLUDES .shtml (Search for them, then remove the #)

Some notes If you don't know what SSI (Server Side Include) is, I suggest looking for more info about it. It is a huge time saver for updating pages (you can update one "menu file" and have hundreds of pages reflect the updated changes). However, it adds additional strain on a server and can potentially make a server slightly less secure, so if you are not using, do not enable it.

Since I use SSI for everything, I changed the settings so *.html files can also run SSI (by default it's only .shtml). So I have AddOutputFilter INCLUDES .shtml .html

AddOutputFilter is completely different than the AddHandler server-parsed way Apache 1.3.x handled it.

• Finding your location to perl• If you do not know where your perl.exe installed to, go to Start -> Search and type in a search for

perl.exe This location is the path to perl you put on the top of all your cgi scripts. If you listened to my advice in the "Install" step, the path should be close to: E:/usr/bin/perl

Turning on cgi (unix)• Some notes For the perl path E:/usr/bin/perl.exe all of these are/were valid. I prefer

the last one, but to each their own.#!E:/usr/bin/perl.exe#!E:/usr/bin/perl#!/usr/bin/perl.exe#!/usr/bin/perl

• Note: for us this path will be something like• #!P:\perl\perl.exe• Testing CGIIf you did not disable ScriptAlias /cgi-bin/ then create a file in

E:/Apache2/cgi-bin/ called hello.cgi and put these three lines in it (if you did disable it, put the CGI file anywhere in your document_root): #!/usr/bin/perl

print "Content-type:text/html\n\n"; print "hello world";

• Restart Apache if it is already running. Now go to http://127.0.0.1/cgi-bin/hello.cgi or localhost and run this script. (scripts in Apache2/cgi-bin/ are read as http://127.0.0.1/cgi-bin/ by default, although if did step (2) you should be able to run CGI scripts from anywhere).

• If you get a hello world in your browser, CGI is running. If you get a 500 error, go to the last entry in E:/Apache2/logs/error.log (or the Review Error Log in the start menu) to see exactly what caused this error.

Port number 80 or 8080(line 53 in my httpd.conf)

# Listen: Allows you to bind Apache to specific IP addresses and/or

# ports, instead of the default. See also the <VirtualHost># directive.## Change this to Listen on specific IP addresses as shown

below to # prevent Apache from glomming onto all bound IP

addresses (0.0.0.0)##Listen 12.34.56.78:80Listen 80

Addhandler (line 418)

• add .pl to this line:

AddHandler cgi-script .cgi .pl

Some perl program examples

• Perl programs will need their first line to include the path to the perl compiler. This line starts with #! (called shebang)

#!c:\perl\bin\perl.exe

Perl statements end in a semi-colon

Hello world: note shebang 1st line points to perl on system

#!c:\perl\bin\perl.exe

print "Content-type:text/html\n\n";

print "hello world";

Deploying the helloworld example:Drop perlscripts into cgi-bin

Using variables

• Simple variables in perl start with a $:

$mystring = "Hello, World";

$mypi = "3.14159";

Note, there is no difference between string, int and float value declaration or assignments.

Using variables#!c:\perl\bin\perl.exeprint "Content-type: text/html \n\n"; # the header$mystring = "Hello, World";$myescapechar = "Welcome to Joe\'s";$myinteger = "5";$myinteger2 = "-5";$mypi = "3.14159";print $mystring; print "<br />"; print $myescapechar; print "<br />"; print $myinteger; print "<br />"; print $myinteger2; print "<br />"; print $mypi;

Vars.pl

Shortcut operators as in java or c++

#!c:\perl\bin\perl.exeprint "content-type: text/html \n\n"; #The header$x = 14;$y = 10;$area = ($x * $y);print $area;print "<br />";$x += 4; #adds 4 to x$y += 12; #adds 12 to y$area = ($x * $y);print $area;

Running vars2

Strings

#!c:\perl\bin\perl.exeprint "content-type: text/html \n\n"; #The header$single = "This string is single quoted";$double = 'This string is double quoted';$userdefined = q^Carrot is now our quote^;print $single; print " "; print $double; print " "; print $userdefined;

Running it

substrings

#!c:\perl\bin\perl.exe

print "content-type: text/html \n\n"; #The header

$mystring = "Welcome to higgins perl examples!";

$twoarguments = substr($mystring, 11);

$threearguments = substr($mystring, 8, 2);

print $twoarguments;

print "<br />";

print $threearguments;

More substrings

#!c:\perl\bin\perl.exe

print "content-type: text/html \n\n"; #The header

$mystring = "Welcome to www.anywhere.com!";

print $mystring;

print "";

substr($mystring, 11) = "www.google.com!";

print $mystring;

Escape char to print $ and @

#!c:\perl\bin\perl.exe#since $ is used to define a var and @ defines an array #we need to use escape chars to put these in our outputprint "Content-type: text/html \n\n"; # the header$string = "David paid \$4.34 for Larry\'s shirt.";$email = "youremail\@youremail.com";print "$string<br />";print "$email<br />";print '$string and $email';

Running escape.pl

Substrings continued

substrings

Interpolation: interpreting variables and instructions

#!c:\perl\bin\perl.exeprint "Content-type:text/html\n\n";$a = 'apples';$b = 'pears';print "$a and $b";

From the previous example

$a = 'apples';

$b = 'pears';

print "$a and $b";

• In the previous example, note that perl “interpreted” variable references even though they were inside the quotes and replaced the $a and $b by their values.

Fibonacci numbers

$old=$next=1;print "$next \n";while($old<1000){$next+=$old;$old=$next-$old;print "$next \n";}#print "$next \n";

Fib programC:\PERL\BIN>perl fib.pl12358132134558914423337761098715972584

Arrays in perl

• Use @ to denote an array. Note recursive reference in the 2nd line below:

@music = ("whistle", "flute");

@moremusic = ("organ", @music, "harp");

@food = ("apples", "pears", "eels");

Array example –some recursive assignments, push and pop, output

#!c:\perl\bin\perl.exeprint "Content-type:text/html\n\n";@music = ("whistle", "flute");@moremusic = ("organ", @music, "harp");@food = ("apples", "pears", "eels");push(@food, "eggs");push(@food, ("eggs", "lard"));$grub = pop(@food);($a, $b) = @food;print @food; # By itselfprint "@food"; # Embedded in double quotesprint @food.""; # In a scalar context

Has output

A hash

• A hash is a key-value pair structure

• It is designated with a % symbol%coins = ( "Quarter" , '25',"Dime" , '10',"Nickel", '05', );

Hash “table”

#!c:\perl\bin\perl.exeprint "content-type: text/html \n\n"; #The header%coins = ( "Quarter" , '25',"Dime" , '10',"Nickel", '05', );while (($key, $value) = each(%coins)){print $key.", ".$value."<br />";}$coins{Penny} = "01";$coins{HalfDollar} = "50";print "<br />"; while (($key, $value) = each(%coins)){print $key.", ".$value."<br />";}

running

Running CGI…an html points to a cgi program<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<!-- reply.html A trivial document to call a simple Perl CGI program --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> XHTML to call the Perl CGI program, reply.cgi </title> </head> <body> <p> This is our first Perl CGI example <br /><br /> <a href = "http://localhost/cgi-bin/reply.cgi"> Click here to run the CGI program, reply.cgi </a> </p> </body></html>

Reply.cgi in the cgi-bin directory#!c:\perl\bin\perl.exe# reply.cgi# This CGI program returns a greeting to the clientprint "Content-type: text/html \n\n", "<?xml version = '1.0' encoding = 'utf-8'?> \n", "<!DOCTYPE html PUBLIC '-//w3c//DTD XHTML 1.1//EN'\

n", "'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'>\n", "<html xmlns = 'http://www.w3.org/1999/xhtml'>\n", "<head><title> reply.cgi example </title></head>\n", "<body>\n", "<h1> Greetings from your Web server! </h1>\n", "</body></html>";

The html

The reply

Popcorn.pl uses CGI module

• Use ppm to install the CGI module:

C:\PERL>ppm install CGI

• (See screenshot in next slide)

ppm install CGI• C:\PERL>ppm install CGI• ====================• Install 'CGI' version 2.91 in ActivePerl 5.8.7.815.• ====================• Installing C:\Perl\html\site\lib\CGI.html• Installing C:\Perl\html\site\lib\CGI\Apache.html• Installing C:\Perl\html\site\lib\CGI\Carp.html• Installing C:\Perl\html\site\lib\CGI\Cookie.html• Installing C:\Perl\html\site\lib\CGI\Fast.html• Installing C:\Perl\html\site\lib\CGI\Pretty.html• Installing C:\Perl\html\site\lib\CGI\Push.html• Installing C:\Perl\html\site\lib\CGI\Switch.html• Installing C:\Perl\html\site\lib\CGI\Util.html• Installing C:\Perl\site\lib\CGI.pm• Installing C:\Perl\site\lib\CGI\Apache.pm• Installing C:\Perl\site\lib\CGI\Carp.pm• Installing C:\Perl\site\lib\CGI\Cookie.pm• Installing C:\Perl\site\lib\CGI\Fast.pm• Installing C:\Perl\site\lib\CGI\Pretty.pm• Installing C:\Perl\site\lib\CGI\Push.pm• Installing C:\Perl\site\lib\CGI\Switch.pm• Installing C:\Perl\site\lib\CGI\Util.pm• Successfully installed CGI version 2.91 in ActivePerl 5.8.7.815.

popcorn.pl uses CGI module#!c:\perl\bin\perl.exe#print "Content-type:text/html\n\n";# popcorn.pl# A CGI program, written using CGI.pm, to process # the popcorn sales form# Initialize total price and total number of purchased items$total_price = 0;$total_items = 0;use CGI ":standard";# First produce the header part of the HTML return valueprint header();print start_html("CGI-Perl Popcorn Sales Form, using CGI.pm");# Set local variables to the parameter valuesmy($name, $street, $city, $payment) = (param("name"), param("street"), param("city"), param("payment"));my($unpop, $caramel, $caramelnut, $toffeynut) = (param("unpop"), param("caramel"), param("caramelnut"), param("toffeynut"));

popcorn.pl# Compute the number of items ordered and the total costif ($unpop > 0) { $cost = 3.0 * $unpop; $total_price += $cost; $total_items += $unpop;} if ($caramel > 0) { $cost = 3.5 * $caramel; $total_price += $cost; $total_items += $caramel;} if ($caramelnut > 0) { $cost = 4.5 * $caramelnut; $total_price += $cost; $total_items += $caramelnut;} if ($toffeynut > 0) { $cost = 5.0 * $toffeynut; $total_price += $cost; $total_items += $toffeynut;}# Produce the result information to the browser and finish the pageprint "<h3>Customer:</h3>\n", "$name <br/>\n", "$street <br/>\n", "$city <br/>\n", "Payment method: $payment <br/><br/>\n", "<h3>Items ordered:</h3> \n", "Unpopped popcorn: $unpop <br/> \n", "Caramel popcorn: $caramel <br/> \n", "Caramel nut popcorn: $caramelnut <br/> \n", "Toffey nut popcorn: $toffeynut <br/><br/> \n", "You ordered $total_items popcorn items <br/>\n", "Your total bill is: \$ $total_price <br> \n";print end_html();

Html Form in htdocs takes an order

Script (in cgi-bin) processes it

Cookies: prints “first visit” or…

cookies1#!c:\perl\bin\perl.exe# day_cookie.pl# - A CGI-Perl program to use a cookie to remember the# day of the last login from a user and display it when runuse CGI ":standard";# Get the existing day cookie, if there was one

@last_day = cookie('last_time');

# Get the current date and make the new cookie

$day_of_week = (qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)) [(localtime)[6]];$month = (qw(January February March April May June July August September October November December)) [(localtime)[4]];$day_of_month = (localtime)[3];@day_stuff = ($day_of_week, $day_of_month, $month);

$day_cookie = cookie(-name => 'last_time', -value => \@day_stuff, -expires => '+5d');

cookies2# Produce the return document# First, put the cookie in the new headerprint header(-cookie => $day_cookie);print start_html('This is day_cookie.pl');# If there was no day cookie, this is the first visitif (scalar(@last_day) == 0) { print "Welcome to you on your first visit to our site <br />";}# Otherwise, welcome the user back and give the date of the # last visitelse { ($day_of_week, $day_of_month, $month) = @last_day; print "Welcome back! <br /> ", "Your last visit was on ", "$day_of_week, $month $day_of_month <br />";}print end_html;

File i/o: processing a data file

C:\PERL\BIN>perl wages.plNames that end in 'son'

JohansonWilliamson

Percent of employees under 40 is: 20Average salary of employees under 40 is: 35000There were no employees under 40 who

earnedover ,000

C:\PERL\BIN>

Wages.pl# wages.pl - An example program to illustrate some of the # features of Perl# Input: A file of lines of employee data, where each line has# name:age:department code:salary# Output: 1. The names of all employees whose names end with "son"# 2. Percentage of employees under 40 years old# 3. Average salary of employees under 40 years old# 4. An alphabetical list of employees who are under 40# years old and who have salaries more than $40,000# Open the data file and display a header for employees # whose names end in 'son'

open(EMPLOYEES, "employees.txt") || die "Can't open employees $!";print "Names that end in 'son'\n\n";# Loop to read and process the employee datawhile (<EMPLOYEES>) {# Increment the number of employees and chop off the newline

$total_employees++; chomp;# Split the input line into its four parts ($name, $age, $dept, $salary) = split(/:/);

Wages.pl# If the name ends in 'son', print the name if ($name =~ /son$/) { print "$name \n"; }# If the employee is under 40, count him or her and add his or her# salary to the sum of such salaries if ($age < 40) { $under_40++; $salary_sum += $salary;# If the salary was over 40,000, add the person and his or her # salary to the hash of such people

if ($salary > 40000) { $sublist{$name} = $salary; } }}# If there was at least one employee, continueif ($total_employees > 0) {# If there was at least one under 40, continue if ($under_40 > 0) {# Compute and display the % of employees under 40 and their# average salaries$percent = 100 * $under_40 / $total_employees; print "\nPercent of employees under 40 is: $percent \n"; $avg = $salary_sum / $under_40; print "Average salary of employees under 40 is: $avg \n";

Wages.pl# If there was at least one under 40 who earned a salary > 40,000,# continue if (keys(%sublist)) { # Sort and display the names of the employees under 40 with # with salaries > 40,000

print "Sorted list of employees under 40", " with salaries > \$40,000 \n"; @sorted_names = sort (keys(%sublist)); print "\nName \t\t Salary\n"; foreach $name (@sorted_names) { print "$name \t \$$sublist{$name} \n"; } } else { print "There were no employees under 40 who earned"; print "over $40,000 \n"; } #** of if (keys(%sublist)) } else { print "There were no employees under 40 \n"; } #** of if ($under_40 > 0)}else { print "There were no employees\n";} #** of if ($total_employees > 0)

Data file

Johanson:44:1234:40000

Williams:32:0011:35000

Smith:65:1010:62333

Abrahams:51:999:90000

Williamson:41:3322:34567

Recommended