What is CGI?

Download Report

Transcript What is CGI?

What is CGI?
• The Common Gateway Interface (CGI) is a
mechanism that allows Web clients to execute
programs on a Web server and to receive their
output. CGI applications are often used to
produce HTML pages on the fly; they are also
used to process the input from an HTML form.
• A gateway is a program that converts
information to a format that a client can use; on
the Web, a gateway is a program that takes nonHTML input or data and produces as output an
HTML page that can be displayed by a Web
browser.
How the CGI program being
executed?
• You can execute a CGI application with
your Web browser by requesting the URL
that corresponds to the application. Most
Web servers store CGI applications in a
directory named cgi-bin. But Webmasters
can define different directories for CGI
applications if they so choose. One
example of the URL for CGI application
could be http://www.domain.name/cgibin/MyCGIApp.cgi.
How can you write a CGI
application?
• You can write a CGI application in any
language that can be executed on your
Web server, compiled or interpreted. This
may include the following, C, C++,
FORTRAN, Perl, etc. The Perl is most
popular language to write the CGI
program.
CGI methods
•
•
To execute a gateway program using CGI, you make a request to the server
to run an application via a method. A method is a way of invoking a CGI
program. In fact, methods are one of the underlying structures of HTTP;
CGI methods rely on HTTP methods. The method you use defines how the
program receives its data. There are three methods used for HTTP. They
are:
The GET method
– When you use the GET method, your script receives its data in the
QUERY_STRING environment variable. Your script will have to parse the
QUERY_STRING environment variable to interpret the data.
– The Get method should be used when the object of the request is to obtain
information from the server, as opposed to changing or adding to the information
on the server.
•
The Post method
– Your script receives its data from stdin (standard input) with the POST method.
The server will not mark the end of the input for your script; there will be no EOF.
Your script must use the CONTENT_LENGTH environment variable to determine
how much data to read from standard input.
CGI Environment variables
•
•
•
•
•
•
•
•
•
•
•
Environment variables are a series of hidden values that the web server sends
to every CGI you run. Your CGI can parse them, and use the data they send.
Variable
Name Value
DOCUMENT_ROOT
The root directory of your server
HTTP_COOKIE
The visitor’s cookie, if one is set
HTTP_HOST
The hostname of your server
HTTP_REFERER
The URL of the page that called your script
HTTP_USER_AGENT
The browser type of the visitor
HTTPS
"on" if the script is being called through a
secure server
PATH
The system path your server is running under
QUERY_STRING
The query string (see GET, below)
REMOTE_ADDR
The IP address of the visitor
CGI Environment variables
•
REMOTE_HOST
•
REMOTE_PORT
•
REMOTE_USER
•
•
REQUEST_METHOD
REQUEST_URI
•
•
•
CGI
SCRIPT_FILENAME
SCRIPT_NAME
(relative
SERVER_ADMIN
SERVER_NAME
SERVER_PORT
SERVER_SOFTWARE
•
•
•
•
The hostname of the visitor (if your server has
reversename-lookups on; otherwise this is the IP
address again)
The port the visitor is connected to on the web
server
The visitor’s username (for .htaccess-protected
pages)
GET or POST
The interpreted pathname of the requested
document or
(relative to the document root)
The full pathname of the current CGI
The interpreted pathname of the current CGI
to the document root)
The email address for your server’s webmaster
Your server’s fully qualified domain name
The port number your server is listening on
The server software you’re using (such as Apache
1.3)
Basics of a Perl Script
• Perl language is something like HTML. It has a clearly
defined syntax, and if you follow those syntax rules, you
can write Perl as easily as you do HTML.
• Rules for the Perl programming:
– Always put this line at the top of your Perl script, no excuses: #!
/usr/bin/perl
This line tells the server that this is a Perl script, and where to
find the Perl interpreter. Make sure it is the place where Perl
interpreter is, and you can always use which perl or whereis
perl to find the correct place.
– Always put a semicolon at the end of every line. If you don’t,
you’ll never, ever, ever get a script to work
First Perl Program
• First perl script example: first.pl
– #!/usr/bin/perl
– print “Hello, world!\n”;
• In the Unix shell, you will need type:
chmod 755 first.pl to change the file
permission to allow you to run the
program. And then when you type ./first.pl
• You will get the output: Hello, world! On
your screen.
Basics of a CGI Script
• A CGI program here is still a Perl script. But one
important difference is that a CGI usually
generates a web page such as form-processing
CGI etc. To write a CGI that’s going to generate
a HTML page, you must include this statement
somewhere in the script, before you print out
anything else:
• Print “Content-type:text/html\n\n”;
• This is a content header that tells the receiving
web browser what sort of data it is about to
receive – in this case, an HTML document.
First CGI example
• First CGI example first.cgi:
–
–
–
–
–
–
#!/usr/bin/perl
print "Content-type:text/html\n\n";
print "<html><head><title>Test Page</title></head>\n";
print "<body>\n";
print "<h2>Hello, world!</h2>\n";
print "</body></html>\n";
• Here if you change the file permissions and run ./first.cgi,
you will find the script will just print out a bunch of HTML.
If you use your browser call
http://www.sbu.ac.uk/~xx/first.cgi,
• It will return a web page with the “Hello, world!” phrase
on it.
First CGI example
• Another way to write the above CGI, without
multiple print statements, is as follows:
–
–
–
–
–
–
–
–
#!/usr/bin/perl
print "Content-type:text/html\n\n";
print <<EndOfHTML;
<html><head><title>Test Page</title></head>
<body>
<h2>Hello, world!</h2>
</body></html>
EndOfHTML
• This is the “here-doc” syntax, and it is very
useful for you to get rid of the typing work.
Perl Variables
• A Scalar Variable
– It stores a single (scalar) value. Perl scalar names are
prefixed with a dollar sign($). So if I want to assign a
value to the variable $stuff, here is how I’d do it:
– A word: $stuff=”rules”;
– A phrase: $stuff=”I like SBU!”
– Numbers: $stuff=2
– You do not need to declare a variable before using it.
A scalar can hold data of any type. You can even add
and subtract like this
– $stuff = 2+2
– $stuff = 4-2
An example for perl scalar
variables:
•
•
•
•
•
•
•
#!/usr/bin/perl
$classname = "Apllied software for IE";
print "Hello there. What is your name?\n";
$you = <STDIN>;
chomp($you);
print "Hello, $you. Welcome to $classname.\n";
Here the STDIN is standard input. And the
chomp($you) is the function to remove the
carriage return from the end of the variable $you
Perl Variables
• Arrays
– An array variable is a variable that holds many scalar
variables in numbered slots. These slots are added as
needed so the variable can grow dynamically. Array
variables usually have the @ (at symbol) in front of
them. Here is an example to declare an array:
– @colors = (“red”,”green”,”blue”)
– In Perl, just C, array indices start with 0, so $color[0]
is equal to “red”. Here $ is again to refer to the single
value of an array.
Perl Variables
• Here is another example to show how
arrays work:
– #!/usr/bin/perl
– # this is a comment
– # any line that starts with a "#" is a comment.
– @colors = ("red","green","blue");
– print "$colors[0]\n";
– print "$colors[1]\n";
– print "$colors[2]\n";
Perl Variables
• Array Functions
– @colors = ("red","green","blue","cyan","magenta",
"black","yellow");
– $elt = pop(@colors); # returns "yellow", the last value of the array.
– $elt = shift(@colors); # returns "red", the first value of the array.
– You can also add data to an array:
– @colors = ("green", "blue", "cyan", "magenta", "black");
– push(@colors,"orange"); # adds "orange" to the end of the
@colors array
– @colors now becomes ("green", "blue", "cyan", "magenta",
"black", "orange").
– @morecolors = ("purple","teal","azure");
– push(@colors,@morecolors); # appends the values in
@morecolors to the end of @colors
– @colors now becomes ("green", "blue", "cyan", "magenta",
"black", "orange", "purple", "teal","azure").
Red
Greem
Blue
Cyan
magenta
black
yellow
• Here are a few other useful functions for array
manipulation:
– @colors = ("green", "blue", "cyan", "magenta",
"black");
– sort(@colors) # sorts the values of @colors
# alphabetically
– @colors now becomes ("black", "blue", "cyan",
"green", "magenta" ).
• You can also use reverse to change the sorting
order
Perl Variables
• Hashes
– A hash is a special kind of array- an associative array, or
paired group of elements. Perl hash name is prefixed with
a percent sign (%), and consist of pairs of elements – a
key and a data value.
– Hash Name key
value
– %pages = ("fred", "http://www.cgi101.com/~fred/",
"beth", "http://www.cgi101.com/~beth/",
"john", "http://www.cgi101.com/~john/" );
– Another way to define a hash would be as follows:
– %pages = ( fred => "http://www.cgi101.com/~fred/",
beth => "http://www.cgi101.com/~beth/",
john => "http://www.cgi101.com/~john/" );
Perl Variables
• An example for using hash:
–
–
–
–
–
–
–
–
–
–
–
–
–
–
#!/usr/bin/perl
#
# the # sign is a comment in Perl
%pages = ( "fred" => "http://www.cgi101.com/~fred/",
"beth" => "http://www.cgi101.com/~beth/",
"john" => "http://www.cgi101.com/~john/" );
print "Content-type:text/html\n\n";
print <<EndHdr;
<html><head><title>URL List</title></head>
<body bgcolor="#ffffff">
<p>
<h2>URL List</h2>
<ul>
EndHdr
Perl Variables
–
–
–
–
–
–
–
–
foreach $key (keys %pages) {
print "<li><a ref=\"$pages{$key}\">$key</a>\n";}
print <<EndFooter;
</ul>
<p>
</body>
</html>
EndFooter
• Foreach is a special for loop iteration
Perl Variables
• Output:
<html><head><title>URL List</title></head>
<body bgcolor="#ffffff">
<p>
<h2>URL List</h2>
<ul>
<li><a href="http://www.cgi101.com/~john/">john</a>
<li><a href="http://www.cgi101.com/~fred/">fred</a>
<li><a href="http://www.cgi101.com/~beth/">beth</a>
</ul>
<p>
</body>
</html>
Perl Variables
• Hash Functions
– delete $hash{$key}
– exists $hash{$key}
– keys %hash
– values %hash
– scalar %hash
# deletes the specified
#key/value pair, and returns the
#deleted value
# returns true if the specified
#key exists in the hash.
# returns a list of keys for that hash
# returns a list of values for that
#hash
# returns true if the hash has
# elements defined (e.g. it’s not an
#empty hash)
Perl Operators
•
Assignment Operators
1. =Makes the value of the variable on the left
side equal to whatever is on the right.
2. +=Adds the value of the right side to the left
side and makes the variable on the left
equal to it.
3. -=Same as above, only subtracts instead of
adds.
Perl Operators
•
Comparison Operators
1. < Returns a true value if the value on the left is less than that
on the right. Otherwise false.
2. > Same as above, but the other way around.
3. >= Returns a true value if the value on the left is greater than or
equal to that on the right. False if not.
4. <= Are we seeing a pattern here?
5. == Returns a true value if the values on both sides are equal;
otherwise returns a false.
6. eq The same as above, but rather than comparing values, it
compares strings of text.
7. != Returns a true value if the value on the right is not equal to
that on the left. False if they are equal.
8. ne Again, same as above, but for strings of text.
Perl Operators
•
Mathematical Operators
1.
2.
3.
4.
5.
* Multiplies the two values together.
/ Divides two values.
+ Adds two values.
- Subtracts two values.
++ Adds 1 to the value on the left (so if $i
were equal to 1, $i++ would equal 2).
6. -- Subtracts 1 from the value on the left.
Flow Controls
• The For Loop
– for ($i = 0; $i <= $#stuff; $i++) {
print "$stuff[$i]";}
• The While Loop
– $stuff = <NAMES>;
– while ($stuff ne "bob") { print "$stuff";
$stuff = <NAMES>;}
Flow Controls
• Foreach Loop
– foreach $slotnum (@stuff) { print
"$slotnum";}
– The foreach loop is really useful for running
through associative arrays since their slots
aren't numbered. Check this out:
– foreach $slotname (keys (%stuff)) { print
"$stuff{$slotname}";}