Previous
Regular Expression 
Next
Using Modules 
Beginner's Tutorial for CGI using Perl Language
Perl And CGI(Common Gateway Interface)

Perl And CGI(Common Gateway Interface)

CGI or Common Gateway Interface is what make the forms work, the counters count and the servers crash. There are many language that could function as CGI language like Perl, C, C++, Tcl, Unix Shell Script etc. By this time, you would have learnt a lot about perl and would be wondering "What in the world is relation between CGI and Perl". CGI scripts can be written in a variety of computer languages, but Perl is without dispute the most used languages for CGI scripting. So we study perl. Now let us see how to use it with Forms and other HTML elements.

By now you officially "know" Perl. You can do things like create small programs, read codes of others etc. without anymore knowledge. But if you want to learn how to use perl as a CGI language, continue reading. And by the way, I do hope that you know HTML. Because I won't be teaching that here.

Lets make a little form. Save the following the following into a file called guestbook.htm

<html><head>
<title>Guestbook</title>
</head>
<body>

<form action="/cgi-bin/guestbook.pl" method="get">
<table>
<tr><td>Name</td><td><input name="name" type="text" value=""></td></tr>
<tr><td>E-Mail</td><td><input name="email" type="text" value=""></td></tr>
<tr><td>Location</td><td><input name="loc" type="text" value=""></td></tr>
<tr><td>Comments</td><td>
<TEXTAREA name="comments" rows="10" cols="32"></TEXTAREA></td></tr>
</table><br><br>
<input type="submit" value="Add Entry">
</form>

</body>
</html>

See the <form action="/cgi-bin/guestbook.pl" method="get"> line? Of course you do.
action="/cgi-bin/guestbook.pl" Tells the server where the CGI script is kept.
method="get" tells the Server which input method is used. There is two input methods - get and post.

Now lets create a perl script to get the input from this file. Create a file called 'guestbook.pl' in the cgi-bin folder. Make sure that the above form points to this file in the action attribute.

First of all the mandatory first line.

#!/usr/local/bin/perl

Now lets get the input...

my $query_string = "";
#Get the input
if ($ENV{REQUEST_METHOD} eq 'POST') {
read(STDIN, $query_string, $ENV{CONTENT_LENGTH});
} else {
$query_string = $ENV{QUERY_STRING};
}
##### We will remove this
print "Content-Type: text/html\n\n";
print "Query String is \n<br> $query_string";
##### We will remove this

Now let us try out the script. I hope you have a server - otherwise nothing doing. Get a server if you want to test you scripts. I use Sambar Server. This server is very easy to use and is very useful while testing your scripts.

Now put the perl file(save the above lines to a file called guestbook.pl) in the cgi-bin folder. If you have sambar server it is usually C:\Program Files\Sambar\cgi-bin. Now copy the guestbook.htm file to the documents folder - the root folder(for sambar this is "C:\Program Files\Sambar\docs" by default). Now fire up your server and open the guestbook.htm file from within the server(For sambar server just open up a Internet Browser like IE and type "http://127.0.0.1/guestbook.htm" in the address bar after opening the server by clicking the sambar shortcut in the start menu.)

If everything went well, you will see the html file we created here. Now enter the below given values
Name - Binny
E-Mail - whatever@wherever.com
Location - Omnipresent
Comments - Hello World! Here I am.
and press the "Add Entry" button.

Now you will be taken to another page. If there is some mistake, it will be an error page. If not, the address bar will look something like this...
http://127.0.0.1/cgi-bin/guestbook.pl?name=Binny&email=whatever@wherever.com&loc=Omnipresent&comments=Hello+World%21+Here+I+am.

This is the information that was passed between two files. Now the content part will look like this.

Query String is
name=Binny&email=whatever@wherever.com&loc=Omnipresent&comments=Hello+World%21+Here+I+am.

This is the data we got from the form. The data will be in this format - <Input name>=<Inputted Data>&<Next Input name>=<Next Inputted Data> and so on Input name stands for the name of the form element in the html file. If you take a look at it you will see that first element is name, next is email and so on. Now we need to convert this data to a more useful format.

So we need to add something to the CGI file. But before that let us remove some lines. Remove the four lines.

##### We will remove this
print "Content-Type: text/html\n\n";
print "Query String is \n<br> $query_string";
##### We will remove this

Did you got emotionally attached to those lines? I warned you they will be removed. Now add the following lines to the guestbook.pl file...

# Split the name-value pairs
@pairs = split(/&/, $query_string);

foreach $pair (@pairs) {
   ($name, $value) = split(/=/, $pair);

   #Converting Hex to English.
   $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
   $value =~ tr/+/ /;

   $FORM{$name} = $value;
}

#Give output
print <<END;

Content-Type: text/html\n\n
<html><head>
<title>Guest book Result</title>
<body>
<h1 align="center">Guest book Results</h1>

$FORM{'name'} came from $FORM{'loc'}. E-mail address is $FORM{'email'}.
Comments : $FORM{'comments'}
</body>
</html>
END

Wow! A new form of outputting. This will print from the print <<END; to where the "END" word appears. This basically means "Print to END". END can be replaced by another word - but replace both occurrences and make sure that it don't appear within the text.

See that we gave the line "Content-Type: text/html\n\n" again? This tells browser that whatever follows is HTML content and not snake oil.

Now we have created a perl file that will take input and give the output in HTML. You can customize the output page as you wish. You may like the following better. Replace the lines "$FORM{'name'} came from $FORM{'loc'}. E-mail address is $FORM{'email'}. Comments : $FORM{'comments'}" with the following.

Dear $FORM{'name'},<BR>Thank You for filling out our Guest Book.
I appreciate this effort in your part.<br><br>
<table>
<tr><td>Name</td><td>$FORM{'name'}</td></tr>
<tr><td>E Mail</td><td>
<a href="mailto:$FORM{'email'}">$FORM{'email'}</a></td></tr>
<tr><td>Location</td><td>$FORM{'loc'}</td></tr>
<tr><td>Comments</td><td>$FORM{'comments'}</td></tr>
</table>

Now our script is really cool - but it don't do the only thing that is expected of a Guest book program - Saving the result to a file. To do that we add the lines,

# Open Guest Book File
open (FILE, ">>guests.txt") || die "Can't open guests.txt: $!\n";
#Write the information to the file
print FILE "$FORM{'name'} came from $FORM{'loc'}.";
print FILE "E-mail address is $FORM{'email'}.";
print FILE "Comments : $FORM{'comments'}\n"; 
close(FILE);

The script is finished. We have created a working guest book program. But I must warn you this script has its limitations. For a better guest book program that I have created, go to http://www.bin-co.com/perl/cgi/guestbook.html. For more guest books by others go to CGI Resources

The full script will look something like this...

#!/usr/local/bin/perl

my $query_string = '';
#Get the input
if ($ENV{REQUEST_METHOD} eq 'POST') {
read(STDIN, $query_string, $ENV{CONTENT_LENGTH});
} else {
$query_string = $ENV{QUERY_STRING};
}

# Split the name-value pairs
@pairs = split(/&/, $query_string);

foreach $pair (@pairs) {
   ($name, $value) = split(/=/, $pair);

   # Making the input English. And removing unwanted things
   $value =~ tr/+/ /;
   $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

   $FORM{$name} = $value;
}

#Give output
print <<START;

Content-Type: text/html\n\n
<html><head>
<title>Guest book Result</title>
<body>
<h1 align="center">Guest book Results</h1>

Dear $FORM{'name'},<BR>Thank You for filling out our Guest Book. 
I appreciate this effort in your part.<br><br>
<table>
<tr><td>Name</td><td>$FORM{'name'}</td></tr>
<tr><td>E Mail</td><td>
<a href="mailto:$FORM{'email'}">$FORM{'email'}</a></td></tr>
<tr><td>Location</td><td>$FORM{'loc'}</td></tr>
<tr><td>Comments</td><td>$FORM{'comments'}</td></tr>
</table>

</body>
</html>
START

# Open Guest Book File
open (FILE, ">>guests.txt") || die "Can't open guests.txt: $!\n";
#Write the information to the file
print FILE "$FORM{'name'} came from $FORM{'loc'}.";
print FILE "E-mail address is $FORM{'email'}.";
print FILE "Comments : $FORM{'comments'}\n"; 
close(FILE);

Now you have a guest book. But it has its limitations and problems. Modify this guest book yourself. Make it better. Make it the best.

Previous
Regular Expression 
Next
Using Modules 
Subscribe to Feed