Docstoc

What is CGI

Document Sample
What is CGI Powered By Docstoc
					    Building CGI Scripts


              By Anchi GUO

Faculty of Pharmacy & Pharmaceutical Sciences
 University of Alberta, Edmonton, AB T6G 2N8
               November 28, 2002
             Objectives

•   What is CGI?
•   How does it work
•   Basic Perl
•   Basic HTML
•   CGI sample scripts
•   Debugging
              What is CGI
• The Common Gateway Interface
• The method by which a web server can
  get data, and display that data to users via
  the web
• CGI can output dynamic information
• A CGI can be written in any programming
  language (ex. C/C++, C Shell, Perl, VB)
        How Is CGI Used?

• Sending Email
• Processing forms (ex. Order form)
• Generating website (ex. CyberCell
  database)
• …
          How does CGI work?

Web Browser               Server                 Application
 (on client)                                      (on server)

                                                    CGI
               1. HTTP             2. Call CGI
               request


   User        4. HTTP             3. CGI
               response            program‘s
                                   response
Sample Script:

#!/usr/bin/perl
print "Hello, world!\n";

#!/usr/bin/perl:
Tells the server that this is a Perl script, and
  where to find the Perl interpreter

print "Hello, world!\n";
Output ―Hello, world‖ on the screen
            Perl Variables
• What is a variable?
  A variable is storage place, where a value
  can be stored for use by a program.
• 3 Perl variable types
     - scalar
     - array
     - hash
                   Scalar
• Is Perl ‗s simplest and most common data
  type
• Replaces many of the common data types
  that other languages use
• Stores a single item: integer, floating point
  number, string, or Boolean value
• Begins with a dollar sign ($)
      $name, $age
                   Array
• An array is a variable that stores multiple
  scalar values

• The entire array can be referenced as a
  single variable

• Array variables start with @
  - @name
  - @PDB_code
             Array (continued)
• Position       0        1      2

     @name      John   Peter   Eric



• Single element
     $name[0]          value: ―John‖
     $name[1]          value: ―Peter‖
     $name[2]          value: ―Eric‖
                   Hash
• Is also called associative array
• Is like normal arrays
• Is indexed by string (key)
• Consists of pairs of elements
         – a key and a value
• Provides very fast lookup of the value
  associated with a key
• Start with % ----- %marks, %age
          Hash (continued)
• Individual element
                             Key     %age
            Keys
                             John     8
 $age{John}    8
 $age{Peter}   10   Values   Peter   10
 $age{Eric}    5
                              Eric    5
             Basic HTML
• HyperText Markup Language

• HTML is the language used to prepare
  hypertext document.

• Web browsers are used to view HTML
  documents and display data to users
             HTML Document
<html>
<head><title>Test Page</title></head>
<body>
<b>Hello, world</b>
</body>
</html>


Document Structure
- Head
- Body
              HTML Tags
• HTML tags are commands, they tell the
  browser how to display the text.

• There are opening and closing versions for
  many tags

     opening tag: <HTML>
     closing tag: </HTML>
        HTML Tags (continued)
• <HTML></HTML> For identifying a text document as an HTML
                        document
• <HEAD></HEAD> For creating the head section of page
• <BODY></BODY> For enclosing the main section of page
• <B></B>       For displaying text in boldface
• <I></I>       For displaying text in italics
• <OL></OL>     For creating ordered lists
• <A></A>       For creating links
• <FORM></FORM> For creating fill-in forms
• <P>           For creating a new paragraph
• <BR>          For creating a line break
• <INPUT>       For creating form elements
       HTML Tags (continued)
The affected text is contained within the tags
• <B>Hello</B> ------- Hello
• <I>Bye!</I> ---------- Bye
• Ordered list
      <OL>
                                    1. Apple
      <LI>Apple</LI>
                                    2. Banana
      <LI>Banana</LI>
      <LI>Orange</LI>               3. Orange
      </OL>
               HTML Form
• <FORM> and </FORM> mark the beginning and
  the end of a form

• Form establishes the relationship between the
  form page and the script that will process the
  current form data

• HTML forms are the user interface that provides
  input to your CGI scripts
      - Collecting data
      - Accepting commands
      HTML Form (continued)
<HTML><HEAD>
<TITLE>My first html page</TITLE></HEAD>
<BODY>
<FORM method=post action=―aftersubmit.cgi‖>
Name: <INPUT type=text name=―uname"><BR>
Password: <INPUT type=password
  name=―upwd"><BR>
<INPUT type=submit>
<INPUT type=reset>
</FORM>
</BODY></HTML>
           The <FORM> Tag
• <FORM method=post action=―aftersubmit.cgi‖>
   Tag attributes specify the properties for the
  element
• method
  determines how the form data is sent to the script
      - GET-- delivers form data by appending it to
                  the URL of the script
      - POST-- sends the data as a body of text
• action
  specifies the address of the script that is going to
  process the current form data
         The <INPUT> Tags
• INPUT
  - is an element of the form
  - creates a wide variety of interface widgets
• <INPUT type=text name=―uname">
• Attribute ―type‖— the appearance and features
       <INPUT type=text>-------text field
       <INPUT type=submit>-----submit button
       <INPUT type=reset>------reset button
       <INPUT type=password>---password field
       <INPUT type=hidden>-----hidden field
 The <INPUT> Tag (continued)
• INPUT attribute "name"
  identifies each user interface element
      <input type=text name=―uname">
      <input type=password name=―upwd">
• INPUT attribute "value"
  contains associated information that is also sent
  to the script.
      <input type=text name=―uname">
      <input type=text name=―uadd">
      <input type=text name=―ucity―
                               value=―Edmonton‖>
           Form Submission
<FORM method=post action = ―aftersubmit.cgi‖>

• The browser assembles the form data (name
  and password) into a series of name/value pairs
• The browser delivers data to the server and then
  the script
      ―aftersubmit.cgi‖
• The script ―aftersubmit.cgi‖ can retrieve the
  element value by using its name (uname and
  upwd)
                   CGI Script
• Is still a Perl script

• Generates a web page

• Needs a content header
    print "Content-type: text/html";
    print "Content-type: image/gif";
                  CGI Script
#!/usr/bin/perl
print "Content-type:text/html\n\n";

print "<html><head>‖;
print ―<title>Test Page</title></head>\n";
print "<body>\n";
print "<b>Hello, world!</b>\n";
print "</body></html>\n";
          How does it work?
• CGI script output:
     <html><head>
     <title>Test Page</title></head>
     <body><b>Hello, world!</b>
     </body></html>
• The output is sent to the server.
• The server captures the output + HTTP headers,
  and sends them back to the browser.
• The browser receives the information, formats
  and displays the text appropriately.
#!/usr/bin/perl

print "Content-type: text/html\n\n";

print "<html><body>";
print "<form method=post action=\―show_param.cgi \">";
print "Name <input type=text name=\"name\"><br>";
print "Address <input type=text name=\"add\"><br>";
print "City <input type=text name=\"city\"><br>";
print "<input type=submit><br>";
print "<input type=hidden name=\‖hidden\‖
   value=\―GMC\‖>";
print "</form>";
print "</body></html>";
            show_param.cgi (1)
#!/usr/bin/perl
print "Content-type: text/html\n\n";
                  the CGI.pm module is used
use CGI;
                     a CGI.pm object $q is created
$q=new CGI;

# retrieve the parameter values
$name=$q->param("name");
$add=$q->param("add");          Parameter names
$city=$q->param("city");
$hidden=$q->param(―hidden‖);
                Explanation (1)
• CGI.pm module
  - is the standard tool for creating CGI scripts in Perl
  - offers many methods: For example:
       - Handling Input (form parameters, environment info)
       - Generating Output (HTML document)
       - Handling Errors (CGI::Carp)
• New CGI object
• param: is a very useful method. It allows you to
  access the parameters submitted to your CGI script
         show_param.cgi (2)
# get the environment information
                         environment variables

$server=$ENV{SERVER_SOFTWARE};
$protocol=$ENV{SERVER_PROTOCOL};
$ref=$ENV{HTTP_REFERER};
$len=$ENV{CONTENT_LENGTH};
         show_param.cgi (3)
print "<HTML><BODY>";
print "Name: $name<BR>";
print "Address: $add<BR>";
print "City: $city<BR>";
print "Hidden: $hidden<BR>";
print "<HR><BR>";
print "Server Software: $server<BR><BR>";
print "HTTP REFERER: $ref<BR><BR>";
print "Content Length: $len<BR><BR>";
print "Remote Address: $Remote_Add<BR><BR>";
print "Server Protocol: $protocol<BR><BR>";
print "Server Name: $Server_Name<BR><BR>";
print "Request Method: $method<BR><BR>";
print "<\/BODY><\/HTML>";
Output
          Reading Data File

• When you build large web application, you
  will need to store data and retrieve it later

• Text files are the simplest way to maintain
  data
      Reading Data File (script)
#!/usr/bin/perl
print "Content-type: text/html\n\n";

$filename=―1ID0.txt‖;
If (open (FILE, $filename) )
{
    @filecontent=<FILE>;     file handle
    close FILE;
    print "<html><body>";
    print ―Data is saved.‖;
    print "</body></html>";
}
                 File Handle
• The file handles are just the things we use when
  we are dealing with files.
• A file handle is associated with a file by the open
  statement.
       open (FILE, $filename)
• All the interaction with a file is done by the file
  handle.
       @filecontent = <FILE> -- get the whole file
       $filecontent = <FILE> ---- get the first line
                  Writing Data File
#!/usr/bin/perl
use CGI;
$q=new CGI;
print "Content-type: text/html\n\n";
$name=$q->param("name");

$outputfile=―users.txt‖;
if (open (OUTPUT, ">>$outputfile"))  # open a file
{
    print OUTPUT "$name\n";         # write the user name to the file
    print "<HTML><BODY>Thank you! $name</BODY></HTML>";
}
Else
{
   print "<HTML><BODY>Error<\/BODY><\/HTML>";
}
    Writing Data File (continued)
• Opening a file for writing
    - For overwriting
             open (OUTPUT, ">>$outputfile")
   - For appending
             open (OUTPUT, ">$outputfile")
• Without ―>>‖ and ―>‖, the file is opened for reading
             open (OUTPUT, "$outputfile")
• Creating the output file and making it writable
      touch users.txt
      chmod a+w users.txt
  Writing and Running a CGI script
• Writing the script using a plain text editor

• Saving the file ―myCGI.cgi‖ in:
      aguo/public_html/cgi-bin/

• Opening a terminal, and type:
      cd public_html/cgi-bin --- change the directory
      chmod 755 myCGI.cgi --- make the script executable

• Opening the browser, and running the script:
      redpoll.pharmacy.ualberta.ca/~aguo/cgi-bin/myCGI.cgi
              Debugging
• Default response of the server:
   "Internal Server Error" --- not useful

• Better ways:
  In the script
      use CGI::Carp qw(fatalsToBrowser);
  In the UNIX shell (check the syntax)
      perl -cw scriptname.cgi
      Debugging (continued)
• use CGI::Carp qw(fatalsToBrowser);
         Debugging (continued)

• perl -cw scriptname.cgi

  syntax error at myCGI.cgi line 23 and line 29, near "print―
  myCGI.cgi had compilation errors.
                  Conclusion
• Basic HTML (structure, tags, forms)
• Basic Perl (variables)
• Basic CGI
  - form processing (retrieving form data)
  - writing data file
  - reading data file
• Steps for working with CGI scripts
  - writing and saving the file to ―public_html/cgi-bin‖
  - changing the file permission to executable
  - running the script
• Debugging
               Thanks

•   Dr. David Wishart
•   Shan Sundararaj
•   Hassan Monzavi
•   Haiyan Zhang

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:18
posted:4/7/2010
language:English
pages:45