CGI Scripts
On submition of the form, the browser open the specified .cgi program with argument using either POST or GET. If the permissions are set correctly, the program will be executed and the output will be sent back to the brower as a webpage. The program is normally written in a scripting language, made executable with chmod and starts with a line that specifies its interpretor:
#!/path/interpreter
In this section we demonstrate a CGI script written in Perl, which starts with
#!/usr/bin/perl
The executable has to return not only the contents of the page but the WWW header information for the page:
Content-type: TYPE, followed by a blank line. |
For example to return a plain, unformatted, text document, the document start with:
Content-type: text/plain
Hello World!
... |
To return a page of formatted HTML, the document start with:
Content-type: text/html
<HTML>
<HEAD>
... |
Here is the source code of guest_book.cgi with comments
#!/usr/bin/perl
#Set save the input string from standard I/O into $buffer
read(STDIN,$buffer,$ENV{'CONTENT_LENGTH'});
#Split the string by the character '&' and save the name=value pairs into @pairs
@pairs=split(/&/,$buffer);
#Go through each pair, split the name and value string by the character '='
#and save them into $FORM
foreach $pair(@pairs){
($name,$value)=split(/=/,$pair);
$value=~tr/+//;
$value=~s/%([a-f A-F 0-9][a-f A-F 0-9])/pack("C",hex($1))/eg;
$FORM{$name}=$value;
}
#Check that the form is not empty
#If not generate a simple webpage using print to tell the error and exit
foreach $check(values%FORM){
if($check eq""){
print"<H2>Please fill in something</H2>";
exit(0);
}
}
$FORM{'message'}=~s/cM\n/<br>\n/g;
#Open the file book.html and print the visitor's information and message into it
$filename="book.html";
open FILE,">> $filename";
print FILE "name: $FORM{'name'}<br>\n";
print FILE "email: <A HREF=\"mailto:$FORM{'email'}\">$FORM{'email'}</A><BR/>\n";
print FILE "message:<BR/>$FORM{'suggest'}<P/>";
close FILE;
#Generate a webpage containing links to the stored guest book
print "Content-type:text/html\n\n";
print "<TITLE>Guest Book</TITLE>";
print "<H1>Guest Book</H1>";
print "<H2>Thanks</H2>";
print "<A HREF=\"book.html\">View the guest book</A>\n";
|
|
Create a file called guest_book.cgi and make it executable:
- chmod 755 guest_book.cgi
- chmod 755 .
- chown -R yourusername *
Then your guest_book.html should work. Click here to see it working
Perl is a very powerful scripting language and is recommeded by our CSG group. You may learn it by reading this beginners tutorial.
But before you dive in, lets move on to the next step, PHP, a scripting language designed for website development. |