Getting Started
Introduction
Perl IDEs
History
Advice
Tools
Mini-Tutorial
Tutorial
Code Snippets

Resources
Top Sites
More Tutorials
Books
Magazines
Articles
NewsLetters
Mailing Lists
NewsGroups
Forums
User Groups
Talk Shows
Blogs
Clothing

GBIC >> Perl >> Information Center Tutorials >> CGI

Perl Information Center Tutorials - CGI
These tutorials were written to help you get a quick, but thorough, understanding of Perl - the scope of the language as well as it's specific capabilities.

Beginners Built-In Functions     Advanced CGI Applications

CGI Scripts
By clicking on a hyperlink or pressing the submit button on a form, a browser can request that a program be run on a server. Typically the program executes and sends the results to the browser for display.

The term Computer Gateway Interface (CGI) refers to the specification of how the server and the executed program exchange data. The executed program is referred to as a CGI Script and may be an interpreted program such as Perl or a compiled program such as Java.

The following code shows a hyperlink that directs the server to execute a Perl script called "mycgi.pl".

  <a href="/cgi-bin/mycgi.pl">Script</a>

And this next code shows an HTML form which requests the server to execute a Perl script called "mycgi.pl" when the Submit button is pressed.

    <form action="cgi-bin/mycgi.pl">
    <input type=text>
    <input type=submit>
    </form>

A form also send the content of all controls within the form, such as the contents of the textbox in the following example.

CGI Response - Redirection to an Existing Web Page
After a CGI script executes it may send the browser a URL to display as is done by the following Perl script.

    #!/usr/bin/perl
    # do anytyhing you want using Perl
    # next line sends user to existing page
    print "Location: http://www.garybeene.com/index.htm" ;

Regardless of what actions the script takes, such as making changes to a database on the server, the only thing a user sees is that the browser display the URL returned by the script.

CGI Response - Dynamic Web Page
A CGI script can also create a web page on-the-fly and send it to the browser. The minimum content that must be returned is shown in this next example. It's the basic text code for a bare bones HTML page.

     <html>
     <body>
     Hello World!
     </body>
     </html>

The following simple Perl script will generate the html code listed above, plus it shows how to add the value of a Perl variable to the output. Variables placed in the output text stream are interpolated by the server.

     #!/usr/bin/perl
     $value = 5
     print "Content-type: text/html\n\n"
     print "<html><body>"
     print $value;
     print "</body></html>"
     

In lieu of using multiple print statements, the "here-document" capability of Perl can also be used, as in the following example. It's multi-line print capability allows an more easily understood format.

     #!/usr/bin/perl
     $value = 5
     print <<stop_html ;
     Content-type: text/html\n\n
     <html>
     <body>
     $value
     </body>
     </html>
     stop_html
     

The 4th line of this script tells the receiving browser that the response from the server is to be treated as an HTML web page. The browser also requires that the following line be blank, which is accomplished using the Perl code "\n\n".

Submitting Data to the Server
When a link is clicked by a user, the command sent to the server contains only the URL of the script to execute.

However, when a form Submit button is pressed, the value of every control in the form is sent to the server and made available to the script which is to be run. The method property of a form determines the format in which the form data will be sent to the server.

     <form action="/myscript.pl" method="post">
     <form action="/myscript.pl" method="get">

If the method is get, the form data is sent to the server by appending it to the requested URL with a question mark followed by the name/value pairs of every control in the form as shown in the following example. To avoid confusion by the server the form data is encoded by converting spaces to plus signs. Also, special characters are sent as %xx, where the xx is the hexadecimal value of the character.

Here's an example of data sent by a form using the get method. The name/value pairs are sent as "name=value". Pairs are separated by an ampersand sign.

     /cgi-bin/myscript.pl?name1=value1&name2=value2

This URL plus text data stream is returned by the server and is visible in the browser as the URL of the response.

If the method is post, then the form sends the data in binary format. In this case, only the CGI script URL is returned by the server. The submitted data stream is not part of the URL of the response.

Web Page Data Extraction
The web server makes the web page data available to the Perl script through the %ENV hash. The %ENV hash key REQUEST_METHOD will have a value of GET or POST and can be detected using the following Perl script.

     if ($ENV{'REQUEST_METHOD'} eq "GET") {
     	$formdata= $ENV{'QUERY_STRING'};
     } else {
     	$formdata = read(STDIN, $formdata $ENV{'CONTENT_LENGTH'}); 
     }
     

With GET, the form data is simply the value of the hash key QUERY_STRING. With POST, the form data must be read in via STDIN, with a byte length corresponding to the value of the hash key CONTENT_LENGTH.

Separating the Name/Value Pairs
In the above script the encoded form information sent by the browser is placed in the $formdata variable. Typically, the information is decoded and placed in a hash for further processing. The control names are used as hash keys and the control values are used as the corresponding hash values. The following code performs the decoding and the creation of the hash.

     @pairs = split(/&/, $qstring); 
     foreach $pair (@pairs) {        
        ($name, $value) = split(/=/, $pair);    
        $name =~ tr/a-z+/A-Z /;                 
        $value =~ s/%(..)/pack("c",hex($1))/ge; 
        $myhash{$name} = $value;                
     }
Now, the hash contains the form data in an easy to access format. The data may be processed, actions taken as needed, and an HTML response sent to the user as described above.

Summary
Web page data is encoded by the browser and sent to the web server, which in turn makes it available to the Perl script. The Perl script extracts the data into a hash for subsequent action. Once the Perl script takes action on the received data, a web page (text output) is returned to the server. The response may contain customized data or simply point to an existing web page (redirection).

If you have any suggestions or corrections, please let me know.