FIT3084: CGI Scripts & Perl


In the previous lecture:

In this lecture:


References:


Limitations

  1. Communication between script and user is indirect.


  2. HTTP is a stateless protocol.


  3. Scripts can be written in a language which is:




The Content Type Field


Revise the CGI example in lecture 18.




The Location Field

Perl

Many CGI scripts are written in Perl.

Well then? What are you waiting for? Please tell me about Perl Syntax.
(Take the link to the lecture material on Perl Syntax before you try to decipher the examples below.)



A Calendar Script

#!/usr/bin/perl
# A calendar script

$CAL = '/usr/bin/cal';
$YEAR = 2001;

# fetch the text of the calendar using the unix cal command
# and chop off the newline character at the end of the returned string
chop($calendar_text = `$CAL $YEAR`);

#print the output html document
print <<END
Content-type: text/html

<HTML>
<HEAD>
	<TITLE>HAL's Calendar</TITLE>
</HEAD>

<BODY bgcolor="#ffffff" text="#000000">
	<BR>
		<B>Hi Dave!</B>
	<BR>
		Here's the calendar you requested.
	<BR>
		Love HAL.
		
	<PRE>
	$calendar_text
	</PRE>
	
	<A HREF="~aland/notes/lect18.html">lecture 18</A>
</BODY>
</HTML>

END


Run the calendar script.



Random Location Script


#!/usr/monash/bin/perl
# randomFile.pl

$FILE_DIRECTORY = 'http://www.cs.monash.edu.au/~aland/notes/randomFiles';
$MAXIMUM = 1000;
$NUMBER_OF_FILES = 3;

#set random seed and select a random file name

srand(time);
$number = int(rand($MAXIMUM));
$number = $number % $NUMBER_OF_FILES;

#return the location of this file to the browser

print "Location: $FILE_DIRECTORY/file$number.html\n\n";



Run the random file script.



Print Environment Variables Script

#!/usr/monash/bin/perl
# print environment variables

&print_HTTP_header;
&print_head;
&print_body;
&print_tail;

# ---- print the HTTP content-type header
# ---- 
sub print_HTTP_header
{
	print "Content-type: text/html\n\n";
}

#  ---- print HTML stuff at head
sub print_head
{
	print <<END;
	<HTML><HEAD>
	<TITLE>Environment Variables</TITLE>
	<BODY bgcolor="#ffffff" text="#000000">
	<H4>Environment Variables</H4>
END
}

# ---- loop through env var's and print them
# ---- 
sub print_body
{
	foreach $env_var (sort keys %ENV)
	{
		print "<STRONG>$env_var:</STRONG> $ENV{$env_var}<BR>\n";
	}
}

# ---- print HTML stuff at tail
# ---- 
sub print_tail
{
	print "<BR><BR>";
	print "<A HREF = \"/~aland/notes/lect18.html\">lecture 18</A>";
	print "</BODY></HTML>";
}



Run the print environment variables script.

Here is the HTML SRC for the call:

<A HREF="/cgi-bin/cgiwrap/~aland/printenv.pl/some/path/stuff
?some+query+stuff">


Note the extra path info and the query string.




This lecture's key point(s):


Courseware | Lecture notes

©Copyright Alan Dorin 2008