What Is CGI ?: Web Browsing
What Is CGI ?: Web Browsing
The Common Gateway Interface, or CGI, is a set of standards that define how
information is exchanged between the web server and a custom script.
The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as
follows:
The Common Gateway Interface, or CGI, is a standard for external gateway programs to
interface with information servers such as HTTP servers.
Web Browsing
To understand the concept of CGI, lets see what happens when we click a hyper link to browse a
particular web page or URL.
Your browser contacts the HTTP web server and demand for the URL ie. filename.
Web Server will parse the URL and will look for the filename in if it finds that file then
sends back to the browser otherwise sends an error message indicating that you have
requested a wrong file.
Web browser takes response from web server and displays either the received file or error
message.
However, it is possible to set up the HTTP server so that whenever a file in a certain directory is
requested that file is not sent back; instead it is executed as a program, and whatever that
program outputs is sent back for your browser to display. This function is called the Common
Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a
PERL Script, Shell Script, C or C++ program etc.
"Content-type:text/html\r\n\r\n";
'<html>';
'<head>';
'<title>Hello Word - First CGI Program</title>';
'</head>';
'<body>';
'<h2>Hello Word! This is my first CGI program</h2>';
print '</body>';
print '</html>';
1;
If you click hello.cgi then this produces following output:
HTTP Header
The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to
understand the content. All the HTTP header will be in the following form
HTTP Field Name: Field Content
For Example
Content-type:text/html\r\n\r\n
There are few other important HTTP headers which you will use frequently in your CGI
Programming.
Header
Description
Content-type: String
The date the information becomes invalid. This should be used by the
browser to decide when a page needs to be refreshed. A valid date
string should be in the format 01 Jan 1998 12:00:00 GMT.
The URL that should be returned instead of the URL requested. You
can use this filed to redirect a request to any file.
Last-modified: String
Content-length:
String
The length, in bytes, of the data being returned. The browser uses
this value to report the estimated download time for a file.
Set-Cookie: String
Description
CONTENT_TYPE
The data type of the content. Used when the client is sending
attached content to the server. For example file upload etc.
CONTENT_LENGTH
The length of the query information. It's available only for POST
requests
HTTP_COOKIE
Return the set cookies in the form of key & value pair.
HTTP_USER_AGENT
PATH_INFO
QUERY_STRING
REMOTE_ADDR
The IP address of the remote host making the request. This can be
useful for logging or for authentication purpose.
REMOTE_HOST
The fully qualified name of the host making the request. If this
information is not available then REMOTE_ADDR can be used to
get IR address.
REQUEST_METHOD
The method used to make the request. The most common methods
are GET and POST.
SCRIPT_FILENAME
SCRIPT_NAME
SERVER_NAME
SERVER_SOFTWARE The name and version of the software the server is running.
Here is small CGI program to list out all the CGI variables. Click this link to see the result Get
Environment
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<font size=+1>Environment</font>\n";
foreach (sort keys %ENV)
{
print "<b>$_</b>: $ENV{$_}<br>\n";
}
1;
The GET method is the defualt method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box. Never use the GET method if
you have password or other sensitive information to pass to the server. The GET method has size
limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible in your CGI
Program through QUERY_STRING environment variable
You can pass information by simply concatenating key and value pairs alongwith any URL or
you can use HTML <FORM> tags to pass information using GET method.
print
print
print
print
print
print
print
print
"<html>";
"<head>";
"<title>Hello - Second CGI Program</title>";
"</head>";
"<body>";
"<h2>Hello $first_name $last_name - Second CGI Program</h2>";
"</body>";
"</html>";
1;
Here is the actual output of the above form, You enter First and Last Name and then click submit
button to see the result.
First Name:
Last Name:
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Hello - Second CGI Program</title>";
"</head>";
"<body>";
"<h2>Hello $first_name $last_name - Second CGI Program</h2>";
"</body>";
"</html>";
1;
Let us take again same examle as above, which passes two values using HTML FORM and
submit button. We are going to use CGI script hello_post.cgi to handle this imput.
<FORM action="/cgi-bin/hello_post.cgi" method="POST">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</FORM>
Here is the actual output of the above form, You enter First and Last Name and then click submit
button to see the result.
First Name:
Last Name:
Physics
Below is checkbox.cgi script to handle input given by web browser for radio button.
#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
if( $FORM{maths} ){
$maths_flag ="ON";
}else{
$maths_flag ="OFF";
}
if( $FORM{physics} ){
$physics_flag ="ON";
}else{
$physics_flag ="OFF";
}
print
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Checkbox - Third CGI Program</title>";
"</head>";
"<body>";
"<h2> CheckBox Maths is : $maths_flag</h2>";
"<h2> CheckBox Physics is : $physics_flag</h2>";
"</body>";
"</html>";
1;
Physics
Below is radiobutton.cgi script to handle input given by web browser for radio button.
#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$subject = $FORM{subject};
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Radio - Fourth CGI Program</title>";
"</head>";
"<body>";
"<h2> Selected Subject is $subject</h2>";
"</body>";
"</html>";
1;
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$text_content = $FORM{textcontent};
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Text Area - Fifth CGI Program</title>";
"</head>";
"<body>";
"<h2> Entered Text Content is $text_content</h2>";
"</body>";
"</html>";
1;
#!/usr/bin/perl
local ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$subject = $FORM{dropdown};
print
print
print
print
print
print
print
print
print
"Content-type:text/html\r\n\r\n";
"<html>";
"<head>";
"<title>Dropdown Box - Sixth CGI Program</title>";
"</head>";
"<body>";
"<h2> Selected Subject is $subject</h2>";
"</body>";
"</html>";
1;
How It Works
Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now,
when the visitor arrives at another page on your site, the cookie is available for retrieval. Once
retrieved, your server knows/remembers what was stored.
Expires : The date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser.
Path : The path to the directory or web page that set the cookie. This may be blank if you
want to retrieve the cookie from any directory or page.
Secure : If this field contains the word "secure" then the cookie may only be retrieved
with a secure server. If this field is blank, no such restriction exists.
Name=Value : Cookies are set and retrviewed in the form of key and value pairs.
Setting up Cookies
This is very easy to send cookies to browser. These cookies will be sent along with HTTP
Header. Assuming you want to set UserID and Password as cookies. So it will be done as follows
#!/usr/bin/perl
print "Set-Cookie:UserID=XYZ;\n";
print "Set-Cookie:Password=XYZ123;\n";
print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT";\n";
print "Set-Cookie:Domain=www.tutorialspoint.com;\n";
print "Set-Cookie:Path=/perl;\n";
print "Content-type:text/html\r\n\r\n";
...........Rest of the HTML Content....
From this example you must have understood how to set cookies. We use Set-Cookie HTTP
header to set cookies.
Here it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that
cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
Retrieving Cookies
This is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable
HTTP_COOKIE and they will have following form.
key1=value1;key2=value2;key3=value3....
#!/usr/bin/perl
$rcvd_cookies = $ENV{'HTTP_COOKIE'};
@cookies = split /;/, $rcvd_cookies;
foreach $cookie ( @cookies ){
($key, $val) = split(/=/, $cookie); # splits on the first =.
$key =~ s/^\s+//;
$val =~ s/^\s+//;
$key =~ s/\s+$//;
$val =~ s/\s+$//;
if( $key eq "UserID" ){
$user_id = $val;
}elsif($key eq "Password"){
$password = $val;
}
}
print "User ID = $user_id\n";
print "Password = $password\n";
This will produce following result
User ID = XYZ
Password = XYZ123
CGI Module
Berkeley cgi-lib.pl