Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

What is "CGI"?

• Common Gateway Interface


• A means of running an executable program
CGI Programming via the Web.
• CGI is not a Perl-specific concept. Almost
any language can produce CGI programs
– even C++ (gasp!!)
• However, Perl does have a *very* nice
interface to creating CGI methods

How Does it Work?


• A program is created, like normal.
• The program must be made user-executable
Forms
• A user visits a web page.
• The web browser contacts the server where the CGI • Most (not all) CGI scripts are contacted
program resides, and asks it to run the program through the use of HTML forms.
– passes Parameters to the program • A form is an area of a web page in which
• similar to command line arguments the user can enter data, and have that data
• The server runs the program with the parameters submitted to another page.
passed in
• When user hits a submit button on the form,
• The server takes the output of the program and returns
it to the web browser. the web browser contacts the script
• The web browser displays the output as an HTML
specified in the form tag.
page

Creating a Form Form Input Types


• Many different ways of getting data from user. Most specified
<form method="post" action="file.cgi"> by <input> tag, type specified by type attribute
… • textfield Î a text box
<input type="submit" value="Submit Form"> • checkbox Î a check box
</form> • radio Î a Radio button
• Method attribute specifies how parameters are passed to the • password Î password field
CGI program. "post" means they’re passed in the HTTP – (text box, characters display as ******)
header (and therefore aren’t seen anywhere). "get" means • hidden Î hidden field (nothing displayed in browser)
they’re passed through the query string of the URL itself, and • submit Î Submit button. Submits the form
therefore seen in the address bar in the web browser.
• reset Î Reset button. Clears form of all data.
• Action attribute specifies which program you want the web
• button Î A button the user can press
browser to contact.
– (usually used w/ javaScript. *shudder*)
• <input> is a tag used to accept User data. type="submit"
specifies a Submit button. When user clicks this button, • file Î field to upload a file
browser contacts file specified in action attribute. • image Î an image user can click to submit form

1
Other Attributes of <input> Inputs that Don’t Use <input>
• <textarea name="...">...</textarea>
• name Î name of input field.
– Multi-line text field. Specify rows and cols attributes,
• value Î value returned from checks & radios; and type any pre-existing text between the tags.
text of submits and buttons; contents of text, • <select name="...">...</select>
password, and hidden
– create a drop-down menu.
• size Î width of text or password – <option value="...">...</option>
• checked Î radio or checkbox ‘turned on’ • Options in the drop down menu. value attribute is the value of
• src Î URL of an image the select input when submitted; text between tags is what is
displayed in the browser for this option

Great. We can input. Now what? Object-Oriented


• Now, we can write a CGI program that takes those • CGI.pm actually defines a class. Therefore, if
inputs, executes some code, and returns an HTML you use CGI; you can then do
page • my $q = CGI->new();
• As with all perl scripts, first line of the program • and access the CGI subroutines as methods of $q.
MUST be the shebang: #!/usr/bin/env perl
• print $q->start_html();
• Next, need to include all the CGI methods. These
are stored in CGI.pm • This allows you to maintain multiple ‘states’
– As you may guess, TMTOWTDI. using more than one instance of the CGI class
• use CGI; • Very useful for complicated programs
• use CGI ":standard";

Function-Oriented
• Alternatively, you can import a set of subroutines to be
called directly, without the need to declare an object.
Outputting from CGI
• Tell Perl which subroutines to import by given a quoted list
in the use statement: • Just as CGI program took ‘input’ from user
• use CGI qw/start_html end_html header/; via web browser, it outputs back to user via
web browser as well.
• CGI.pm defines sets of these functions. Most common is
the ‘standard’ set: • STDOUT is redirected to the web browser
• use CGI qw/:standard/; that contacted it.
• For a full list of which functions are in which sets, examine • This means you don’t have to learn any new
the CGI.pm file, looking at the variable %EXPORT_TAGS output functions. print() will now
throw data to the web browser.
• Now, you can call all the CGI subroutines directly, without
declaring any objects

2
Beginning a CGI Program Now Create your Output
• #!/usr/bin/env perl • Remember, you’re building an HTML page in the
use strict; output. So you must follow the HTML format:
use warnings;
• print "<html>\n<head>\n<title>My CGI
use CGI qw/:standard/;
print header('text/html'); Program</title>\n</head>\n<body>\n";
• header() prints the HTTP header to web browser. • CGI.pm gives you a better way to do this. We’ll get to
The argument is the MIME type of the it soon.
forthcoming data.
– Defaults to text/html, so you can usually just leave the
argument out.

Where’d Those Inputs Go? Dump()


• They were passed into the CGI program as parameters.
You can retrieve them using the param() function. • subroutine defined in CGI.pm. Retrieves list
• Called in scalar context without any arguments, returns of parameters and creates an HTML list of
the number of parameters passed to the script all parameters and all values.
– my $num_params = param();
• Like most CGI functions, doesn’t print
• Called in list context without an argument, returns names anything. You must manually print the
of all parameters.
– my @params = param(); return value of the function call.
• Called in scalar context, takes name of one parameter, and • print Dump;
returns value of that parameter
– my $name = param('name');
• Called in list context w/ an argument, returns array of all
values for that parameter (ex, for checks and dropdowns)
– my @colors = param('color');

HTML Shortcuts More shortcuts


• For tags with attributes, place name/value attributes in a
• CGI.pm gives you methods to create HTML hash reference as the first argument. The string enclosed in
code without actually writing HTML. tag is the second argument. Ex:
• print a(
• most HTML tags are aliased to CGI functions. {href=>'sample.html', target=>'top'},
• unpaired tags: 'Sample file'
– print br(); # sends <br> to browser );
– print p; # sends <p> to browser • Produces:
• paired tags: • <a href="sample.html"
– print strong('Bold text'); target="top">Sample file</a>
#<strong>Bold text</strong> • You may think this is needless amounts of extra learning,
– print em('Italic'); with no time or length benefits
#<em>Italic</em> – You’re probably right. In this case.

3
start_html() and end_html() HTML Form Shortcuts
• start_html() can take one parameter, the title. • For full list of Form shortcuts, see "FORM ELEMENTS" in
perldoc CGI
• print start_html("My title");
– or http://search.cpan.org/dist/CGI.pm/CGI.pm
– <html><head><title>My title
</title></head><body> • Each one takes parameters as name/value pairs. Name starts
with a dash. Most parameters are optional
• Can also take named parameters, with attributes to
• print startform(-method=>'post', -action=>
give to <body> tag:
'foo.cgi')
• print start_html (-title=>'My – default method is post. default action is current script
Title', -bgcolor=>'Red');
• produces: <form method="post" action="foo.cgi">
– <html><head><title>My title
</title></head><body bgcolor="Red"> • print endform(); # produces </form>
• print end_html;
– </body></html>

Input Shortcuts Programmer Beware


• "default" in input methods is value used *first*
• textfield(-name=>"MyText",
time script is loaded only. After that, they hold
-default =>"This is a text box") the values they had the last time the script was
– <input type="text" name="MyText" run.
value="This is a text box"> • to override (ie, force default value to appear), set
• All HTML Form input shortcuts are similar. Again, parameter -override=>1 inside input
see the perldoc for full list and description. method:
• textfield(-name=>"foo",
-default =>"bar",
-override=>1);

Avoid Conflicts All in One file


• Some HTML tags have same name as internal Perl • One common method of CGI programming is to make both the form
functions. Perl will get very confused if you try to use the and the response all in one script. Here’s how you do that…
CGI shortcut methods to print these tags… • #!/usr/bin/env perl
use strict;
• <tr> – table row. conflicts with tr///
use warnings;
– use Tr() or TR() instead use CGI qw/:standard/;
• <select> – dropdown list. conflicts with select(). print header;
– use Select() instead • if (!param()){ #no parameters
• <param> - pass parameters to Java applet – conflicts with print start_html("Here’s a form");
param(). print startform;
– use Param() instead #create your form here…
print endform;
• <sub> - Make text subscripted. Conflicts with sub
keyword. • } else { #parameters passed, form submitted
print start_html("Here’s the result");
– Use Sub() instead
#display the results of the submitting form
}

4
Running CGI on CS machines
• RCS does not grant CGI privileges. CGI on CS
– We'll need to use our CS Dept accounts
– If you never signed up from the course webpage, or mistakingly • The CGI-enabled server is cgi2.cs.rpi.edu
said you had a CS account when you don't, you need to email me
ASAP.
• To run your scripts on cgi2.cs
– if you never changed your temporary password, or forgot what you – set shebang: #!/usr/bin/env perl
changed your password to, email labstaff@cs.rpi.edu and request a – make file user-executable
password reset – put the file in public.html/cgi-bin directory
• The remote-access machine you should use is named – Make sure public.html and cgi-bin are world-executable
solaris.remote.cs.rpi.edu – go to http://cgi2.cs.rpi.edu/~rcsid/cgi-bin/filename.cgi
• SSH into this machine just as you have been using – see "Steps For CGI" in handouts for detailed process
rcs-sun4.rpi.edu
• If all goes well, your script’s output will be displayed.
– if they don't exist, create public.html/ and public.html/cgi-bin
directories. • If all does not go well, you’ll get HTTP 500
• Create your .cgi file in the cgi-bin directory.

Debugging CGI::Carp
• Enables you to view your compilation errors in the browser,
• Debugging a CGI program can be a very frustrating rather than searching for them in the server's error logs.
task. • #!/usr/bin/env perl
• If there are any compilation errors whatsoever, the use strict;
web browser will simply display use warnings;
500 Internal Server Error use CGI qw/:standard/;
• It will also tell you that "more information may be use CGI::Carp (
found in the server logs". 'warningsToBrowser',
'fatalsToBrowser'
• Those server logs are located on the CS System at: );
/servers/cgi2/logs/error.log print header;
• There is, of course, a nicer alternative… warningsToBrowser(1);
• fatal errors will now be displayed in the browser.
• Warnings will be displayed as HTML comments (view the
source of your page to see them)

Debugging process
• If you get HTTP 500, even with using CGI::Carp...
• Try running your script from the command line
– ssh into cgi2.cs.rpi.edu, change to your public.html/cgi-
bin directory, and run your script
• Run it *directly*: ./prog.cgi, not perl prog.cgi
• If that appears to work without problems, then check
the server logs
– try grep'ing for your username or filename:
grep lallip error.log
grep my_cgi.cgi error.log

You might also like