Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Basic Examples of CGI with Perl

The Basics

Basic Examples of CGI with Perl

by  goBoating  Posted    (Edited  )
This FAQ attempts to give very simple examples
of using Perl to write CGI code for the UNIX
boxes. While UNIX flavored, most of this should
be true for Windows boxes (Windows and IIS handle
user permissions and such differently).
This is not an exhaustive treatment. For that,
buy a book, or check out www.perl.com or many other
online resources.

WHAT IS CGI?
CGI => [red]C[/red]ommon [red]G[/red]ateway [red]I[/red]nterface
CGI is a set of rules, which if followed, will
let you ask a web server to run a program for you.
There are rules that apply to a web page which calls
the program and there are rules for the program.
You can write CGI in any language that can obey the rules.
For a complete treatment of these rules, please buy
a book or see www.perl.com or.....;-)

[red]IMPORTANT[/red] => Doing CGI on any server minimally opens
security cracks and possibly opens gaping holes
in that server. Please check some of the resources
on server security and CGI. This is good place to
start, http://www.w3.org/Security/faq/

Very briefly....

#################################################
SIMPLEST CGI
++++++++++++
#################################################
As stated above, CGI will let you run a program on
a CGI capable web server. In it's simplest incarnation,
no inputs are needed. You can write a very simple piece
of CGI that simply prints something, like, the ubiquitous,
'Hello World'. Copy and Paste the following code chunk
into a text file,
- change the top line to point at your perl installation,
- save it into a cgi-bin dir,
- set the execute bits,
- and hit it via a browser.

You should see 'Hello World'.
If you do not, then you probably:
- did not change the first line correctly, or
- convert from a DOS file format to UNIX, or
- you forgot to set the execute bits(chmod +x filename), or
- you did not put the file in a valid cgi dir in the web
servers directory tree.

Also,
the "Content-type...." line must be exactly as shown.
There are variations on that theme, but, make this work first.

Code:
#!/usr/local/bin/perl
print "Content-type: text/html\n\n";
print "<HTML><HEAD><TITLE>A NEW CGI PAGE</TITLE></HEAD>\n";
print "<BODY><P>Hello World</P></BODY></HTML>";

You can fire the cgi code with a link to it, like
Code:
<a href="http://www.someserver.com/cgi-bin/simple.cgi">simple CGI</a>
or,
just type the uri into the address slot in your browser.


#################################################
HTML INPUT FORM
+++++++++++++++
#################################################
To send inputs from an HTML form to CGI application, you
need to obey the rules for setting up your HTML input page.
You will need a FORM tag specifying an ACTION (what CGI to
run on what server) and a METHOD (how to decode the input).
Like,
Code:
<FORM ACTION="http://www.server.com/cgi-bin/code.cgi" METHOD="POST">

Here is a very simple HTML input form that askes for an
email address. Note that the ACTION attribute in the
FORM tag must point at your CGI code. Also, in the
<INPUT..> tag, the NAME attribute will name the value
in the CGI code below.

Code:
<HTML>
<HEAD><TITLE>Most Basic CGI Input Page</TITLE></HEAD>
<BODY>
<FORM ACTION="/cgi-bin/simple.cgi" METHOD="POST">
<P>email, please: 
<INPUT TYPE="TEXT" WIDTH="25" NAME="Email_Address">
</P></FORM></BODY></HTML>

#################################################
Verbose CGI Catching One Input
++++++++++++
#################################################

The following is a piece of CGI that does not use any of the
CGI modules that are available. I include this verbose example
to illustrate the flow of decoding the CGI input parameters.
I suggest that after cruising through this example, you go ahead
and use CGI.pm or one of the other available modules. Also,
some people are put off by the object syntax used by most of
the modules. Please go ahead and get comfortable with it.
You will be glad you did. Note that the email address is
retreived from the input using EXACTLY the same name as
used in the HTML to name the input field.
You can copy/paste it into a file, make sure you convert
to UNIX file flavor, chmod +x, and hit from the above HTML page.

Code:
#!/usr/local/bin/perl
#
%FORM = &cgidecode();
$email = $FORM{Email_Address};
print "Content-type: text/html\n\n";
print "<HTML><HEAD><TITLE>Catching an email</TITLE></HEAD>\n";
print "<BODY><P>Address is: $email.</P></BODY></HTML>";

sub cgidecode 
    {
    local(%vars, $val, $key, $last, $buffer, $pair, @pairs);
    # Checking the form method (GET or POST) used 
    # in the HTML code. POST method sends data to
    # standard input, but GET adds it to the URL 
    # and stores it in QUERY_STRING.
    if ($ENV{'REQUEST_METHOD'} eq "POST") 
        { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); }
    else 
        { $buffer = $ENV{'QUERY_STRING'}; }

    # Splitting up the data fields and store in array @pairs, 
    # they are seperated with &
    @pairs = split(/&/, $buffer);

    # Splitting the variable names and the values and storing 
    # them in the assoc. array %vars
    foreach $pair (@pairs) 
        {
        ($key, $val) = split(/=/, $pair);
        $val =~ s/\+/ /g;
        $val =~ s/%(..)/pack("C",hex($1))/eg;
        if ($key eq $last) {$vars{$key} .= " ".$val; }
        else { $vars{$key} = $val; }
        $last = $key;
        }
    return(%vars);
    }

#################################################
A Little More Concise
++++++++++++
#################################################

The following code does the same thing, but, using the CGI.pm
module. You can copy/paste it into a file, make sure you convert
to UNIX file flavor, chmod +x, and hit from the above HTML page.

Code:
#!/usr/local/bin/perl
use CGI;

# instantiate a new CGI object.  Call it $q.
$q = new CGI;
print $q->header;
print $q->start_html;
# retreive the Email_Address parameter submitted in the HTML
$email = $q->param('Email_Address');

# check to see if it looks like an email.
unless ($email =~ /.*@.*\.\w+/) 
    { &killme("Not a valid email address"); }
print "<P>Email is $email</P>\n";
print $q->end_html;

sub killme {
print "<P>$_[0]</P>";
print $q->end_html;
die;
}


#################################################
Input Page and Results with the
Piece of CGI
++++++++++++
#################################################

OK, now an example of a piece of CGI that produces the input
page and parses the results, if there are any.

Code:
#!/usr/local/bin/perl
use CGI;
$cgi = new CGI;
$this_prog = $cgi->self_url;

print $cgi->header,$cgi->start_html(-title=>"A Simple CGI Input Page");

my $email = $cgi->param('email');
if ($email)
    {
    # check to see if it looks like an email.
    unless ($email =~ /.*@.*\.\w+/) 
        { &killme("Not a valid email address"); }
    print "<P>Email is $email</P>\n";
    print $q->end_html;
    }
else
    { # no email submitted, we must need to send the input page.
    print $cgi->center,
        $cgi->h3($header), 
        $cgi->start_form(-method=>'POST', -action=>"$this_prog"),
        "Your email address: ",
        $cgi->textfield(-name=>'email',
                        -size=>'25',
                        -maxlength=>'40'),
        ' ',$cgi->submit(-name=>'Submit', -value=>'submit'),
        $cgi->endform,"</center>";
    }
sub killme
{
print "<P>$_[0]</P>";
print $q->end_html;
die;
}


Oh yeah, remember TIMTOWTDI with Perl ;-)
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top