Perl CGI Programming
What is CGI
CGI is currently maintained by NCSA, which defines CGI as follows:
CGI (Common Gateway Interface) is a program running on a server such as an HTTP server, providing an interface with the client's HTML pages.
Web browsing
To better understand how CGI works, we can follow the flow of clicking a link or URL on a web page:
- 1. Use your browser to access a URL and connect to the HTTP web server.
- 2. After receiving the request information, the Web server parses the URL and checks whether the requested file exists on the server. If it exists, the file content is returned; otherwise, an error message is returned.
- 3. The browser receives the information from the server and displays the received file or the error message.
A CGI program can be a Python script, PERL script, SHELL script, C or C++ program, and so on.
CGI architecture diagram

Web server support and configuration
Before you start CGI programming, make sure your web server supports CGI and has a CGI handler configured.
Apache CGI support configuration:
Set up the CGI directory:
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
All HTTP servers store CGI programs in a preconfigured directory. This directory is called the CGI directory and, by convention, is named /var/www/cgi-bin.
The extension for CGI files is .cgi, and Perl can also use the .pl extension.
By default, the cgi-bin directory on Linux servers is configured under /var/www.
If you want to specify another directory for running CGI scripts, modify the httpd.conf configuration file as shown below:
AllowOverride None
Options +ExecCGI
Order allow,deny
Allow from all
Add the .pl suffix in AddHandler so that we can access Perl script files ending in .pl:
AddHandler cgi-script .cgi .pl .py
Your First CGI Program
Below we create a test.cgi file, with the following code:
test.cgi code
#!/usr/bin/perl
"
Content-type:text/html
\r
\n
\r
\n
"
;
'
'
;
'
'
;
'
'
;
'
'
;
'
'
;
'
'
;
'
Hello Word!
'
;
'
The first CGI program from Runoob Tutorial.
'
;
'
'
;
'
'
;
1
;
Then open http://localhost/cgi-bin/test.cgi in the browser, and the output is as follows:

The output content on the first line of the script, "Content-type:text/html\r\n\r\n", is sent to the browser and tells the browser that the content type to display is "text/html".
HTTP headers
The "Content-type:text/html" in the test.cgi file content is part of the HTTP header; it is sent to the browser to tell the browser the content type of the file.
The HTTP header format is as follows:
HTTP 字段名: 字段内容
For example:
Content-type:text/html\r\n\r\n
The following table describes HTTP header information commonly used in CGI programs:
| Header | Description |
|---|---|
| Content-type: | The MIME information corresponding to the entity in the request. For example: Content-type:text/html |
| Expires: Date | The date and time when the response expires |
| Location: URL | Used to redirect the recipient to a location other than the requested URL to complete the request or identify a new resource |
| Last-modified: Date | The last modification time of the requested resource |
| Content-length: N | The content length of the request |
| Set-Cookie: String | Set an HTTP Cookie |
CGI Environment Variables
All CGI programs receive the following environment variables, which play an important role in CGI programs:
| Variable Name | Description |
|---|---|
| CONTENT_TYPE | The value of this environment variable indicates the MIME type of the information being passed. Currently CONTENT_TYPE is generally application/x-www-form-urlencoded, indicating that the data comes from an HTML form. |
| CONTENT_LENGTH | If the server transfers information to the CGI program using POST, this environment variable is the number of bytes of valid data that can be read from standard input STDIN. This environment variable must be used when reading the input data. |
| HTTP_COOKIE | The COOKIE contents on the client. |
| HTTP_USER_AGENT | Provides client browser information including the version number or other proprietary data. |
| PATH_INFO | The value of this environment variable is the additional path information immediately following the CGI program name. It often appears as a parameter of the CGI program. |
| QUERY_STRING | If the server passes information to the CGI program using GET, the value of this environment variable is the information being passed. It follows the CGI program name, separated by a question mark '?'. |
| REMOTE_ADDR | The value of this environment variable is the IP address of the client sending the request, such as 192.168.1.67 above. This value is always present, and it is the only identifier the web client needs to provide to the web server, so it can be used in CGI programs to distinguish different web clients. |
| REMOTE_HOST | The value of this environment variable contains the host name of the client sending the CGI request. If the lookup is not supported, this environment variable need not be defined. |
| REQUEST_METHOD | Provides the method by which the script was invoked. For scripts using the HTTP/1.0 protocol, only GET and POST are meaningful. |
| SCRIPT_FILENAME | The full path of the CGI script |
| SCRIPT_NAME | The name of the CGI script |
| SERVER_NAME | This is the host name, alias, or IP address of your WEB server. |
| SERVER_SOFTWARE | The value of this environment variable contains the name and version of the HTTP server invoking the CGI program. For example, the value above is Apache/2.2.14(Unix) |
Below is a simple CGI script that outputs the CGI environment variables:
Example
#!/usr/bin/perl
"
Content-type: text/html
\n
\n
"
;
'
'
;
"
Environment variables:
\n
"
;
foreach
(
sort
keys
%ENV
)
{
"
$_
:
$ENV
{
$_
}
\n
"
;
}
1
;
File Download
If we want to implement file downloads through Perl CGI, we need to set different header information, as shown below:
Example
#!/usr/bin/perl
HTTP Header
"
Content-Type:application/octet-stream; name=
"
FileName
"
\r
\n
"
;
"
Content-Disposition: attachment; filename=
"
FileName
"
\r
\n
\n
"
;
Actual File Content will go hear.
open
(
FILE
,
"
" ) ; while ( read ( FILE , $buffer , 100 ) ) { print ( " $buffer " ) ; } The GET method sends encoded user information to the server; the data is included in the URL of the requested page, separated by a "?" as shown below: Some other notes about GET requests: The following is a simple URL that uses the GET method to send two parameters to the test.cgi program: The following is the code for the test.cgi file: #!/usr/bin/perl local ( $buffer , @pairs , $pair , $name , $value , %FORM ) ; $ENV { ' REQUEST_METHOD ' } =~ tr / a z / A Z /; if ( $ENV { ' REQUEST_METHOD ' } eq " GET " ) { $buffer = $ENV { ' QUERY_STRING ' } ; } @pairs = split ( /&/, $buffer ) ; foreach $pair ( @pairs ) { ( $name , $value ) = split ( /=/, $pair ) ; $value =~ tr /+/ / ; $value =~ s / % ( .. ) / pack ( " C " , hex ( $1 ) ) / eg ; $FORM { $name } = $value ; } $name = $FORM { name } ; $url = $FORM { url } ; print " Content-type:text/html \r \n \r \n " ; print " " ; print " " ; print ' ' ; print ' ' ; print " " ; print " " ; print " $name URL: $url " ; print " " ; print " " ; 1 ; View in the browser, the output is as follows: The following is an HTML form that uses the GET method to send two pieces of data to the server; the server script submitted to is also the test.cgi file. The test.html code is as follows: Runoob Tutorial(runoob.com)
title
head Site name: Site URL: In the browser, the execution result is as follows: Using the POST method to pass data to the server is safer and more reliable; sensitive information such as user passwords should be sent with POST. The following is also test.cgi, which can also handle POST form data submitted by the browser: #!/usr/bin/perl local ( $buffer , @pairs , $pair , $name , $value , %FORM ) ; $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 ' } ; } @pairs = split ( /&/, $buffer ) ; foreach $pair ( @pairs ) { ( $name , $value ) = split ( /=/, $pair ) ; $value =~ tr /+/ / ; $value =~ s / % ( .. ) / pack ( " C " , hex ( $1 ) ) / eg ; $FORM { $name } = $value ; } $name = $FORM { name } ; $url = $FORM { url } ; print " Content-type:text/html \r \n \r \n " ; print " " ; print " " ; print ' ' ; print ' ' ; print " " ; print " " ; print " $name URL: $url " ; print " " ; print " " ; 1 ; The following is an HTML form that uses the GET method to send two pieces of data to the server; the server script submitted to is also the test.cgi file. The test.html code is as follows: Runoob Tutorial(runoob.com)
title
head Site name: Site URL: In the browser, the execution result is as follows: checkbox is used to submit one or more option values; the test.html code is as follows: Runoob Tutorial(runoob.com)
title
head Runoob Tutorial Select website " />
form
body
html The following is the code for the test.cgi file: #!/usr/bin/perl local ( $buffer , @pairs , $pair , $name , $value , %FORM ) ; $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 ' } ; } @pairs = split ( /&/, $buffer ) ; foreach $pair ( @pairs ) { ( $name , $value ) = split ( /=/, $pair ) ; $value =~ tr /+/ / ; $value =~ s / % ( .. ) / pack ( " C " , hex ( $1 ) ) / eg ; $FORM { $name } = $value ; } if ( $FORM { runoob } ) { $runoob_flag = " ON " ; } else { $runoob_flag = " OFF " ; } if ( $FORM { google } ) { $google_flag = " ON " ; } else { $google_flag = " OFF " ; } print " Content-type:text/html \r \n \r \n " ; print " " ; print " " ; print ' ' ; print ' ' ; print " " ; print " " ; print " $runoob_flag " ; print " $google_flag " ; print " " ; print " " ; 1 ; In the browser, the execution result is as follows: Radio passes only one piece of data to the server; the test.html code is as follows: Runoob Tutorial(runoob.com)
title
head Runoob Tutorial The test.cgi script code is as follows: #!/usr/bin/perl local ( $buffer , @pairs , $pair , $name , $value , %FORM ) ; $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 ' } ; } @pairs = split ( /&/, $buffer ) ; foreach $pair ( @pairs ) { ( $name , $value ) = split ( /=/, $pair ) ; $value =~ tr /+/ / ; $value =~ s / % ( .. ) / pack ( " C " , hex ( $1 ) ) / eg ; $FORM { $name } = $value ; } $site = $FORM { site } ; print " Content-type:text/html \r \n \r \n " ; print " " ; print " " ; print ' ' ; print ' ' ; print " " ; print " " ; print " $site " ; print " " ; print " " ; 1 ; In the browser, the execution result is as follows: Textarea passes multiple lines of data to the server; the test.html code is as follows: Runoob Tutorial(runoob.com)
title
head Enter content here...
textarea The test.cgi script code is as follows: #!/usr/bin/perl local ( $buffer , @pairs , $pair , $name , $value , %FORM ) ; $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 ' } ; } @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 " Content-type:text/html \r \n \r \n " ; print " " ; print " " ; print ' ' ; print ' ' ; print " " ; print " " ; print " $text_content " ; print " " ; print " " ; 1 ; In the browser, the execution result is as follows: The HTML dropdown code is as follows: Runoob Tutorial(runoob.com)
title
head Runoob Tutorial
option The test.cgi script code is as follows: #!/usr/bin/perl local ( $buffer , @pairs , $pair , $name , $value , %FORM ) ; $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 ' } ; } @pairs = split ( /&/, $buffer ) ; foreach $pair ( @pairs ) { ( $name , $value ) = split ( /=/, $pair ) ; $value =~ tr /+/ / ; $value =~ s / % ( .. ) / pack ( " C " , hex ( $1 ) ) / eg ; $FORM { $name } = $value ; } $site = $FORM { dropdown } ; print " Content-type:text/html \r \n \r \n " ; print " " ; print " " ; print ' ' ; print ' ' ; print " " ; print " " ; print " $site " ; print " " ; print " " ; 1 ; In the browser, the execution result is as follows: A major drawback of the http protocol is that it does not identify users, which causes great inconvenience for programmers; the cookie feature was introduced to make up for this. A cookie is data written to the client's hard disk through the client's browser while the client visits a script; when the client visits the script again, the data is retrieved, making identity determination possible. Cookies are often used for authentication. http cookies are sent through http headers, before the file is transferred. The syntax of the Set-Cookie header is as follows: Setting cookies is very simple; cookies are sent separately in the HTTP header. The following example sets UserID, Password, and expires in a cookie: #!/usr/bin/perl print " Set-Cookie:UserID=XYZ; \n " ; print " Set-Cookie:Password=XYZ123; \n " ; print " Set-Cookie:Expires=Tuesday, 31-Dec-2017 23:12:40 GMT " ;\ n " ; print " Set Cookie : Domain = www . runoob . com ;\ n " ; print " Set Cookie : Path =/ perl ;\ n " ; print " Content type : text / html \ r \ n \ r \ n " ; ...........other HTML content Retrieving cookie information is also very simple: cookie information is stored in the CGI environment variable HTTP_COOKIE, in the following format: #!/usr/bin/perl $rcvd_cookies = $ENV { ' HTTP_COOKIE ' } ; @cookies = split / ; / , $rcvd_cookies ; foreach $cookie ( @cookies ) { ( $key , $val ) = split ( /=/, $cookie ) ; $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 " ; The output of the above example is: Perl provides many built-in CGI modules; the following two are commonly used:
Transferring data with the GET method
http://www.test.com/cgi-bin/test.cgi?key1=value1&key2=value2
Simple URL example: GET method
/cgi-bin/test.cgi?name=Runoob Tutorial&url=http://www.runoob.com
Example
Read text information
Read name/value pair information

Simple form example: GET method
test.html file code
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title><body>
<form action="/cgi-bin/test.cgi" method="get"><input type="text" name="name">
<br/><input type="text" name="url" />
<input type="submit" value="Submit" />form body html>
Passing data with the POST method
test.cgi code
Read text information
Read name/value pair information
test.html code
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title><body>
<form action="/cgi-bin/test.cgi" method="post"><input type="text" name="name">
<br/><input type="text" name="url" />
<input type="submit" value="Submit" />form body html>
Passing checkbox data through a CGI program
test.html code
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title><body>
<form action="/cgi-bin/test.cgi" method="POST" target="_blank">
<input type="checkbox" name="runoob" value="on" /><input type="checkbox" name="google" value="on" />Google>
<input type="submit" value=">test.cgi code
Read information
Read name/value pair information
Runoob Tutorial selected state:
Google selected state:

Passing radio data through a CGI program
test.html code
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title><body>
<form action="/cgi-bin/test.cgi" method="post" target="_blank">
<input type="radio" name="site" value="runoob" /><input type="radio" name="site" value="google" />Google>
<input type="submit" value="Submit" />form body html>test.cgi code
Read information
Read name/value pair information
Selected website

Passing textarea data through a CGI program
test.html code
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title><
body
<
form
action
=
"
/cgi-bin/test.cgi
"
method
=
"
post
"
target
=
"
_blank
"
<
textarea
name
=
"
textcontent
"
cols
=
"
40
"
rows
=
"
4
"<input type="submit" value="Submit" />form body html>test.cgi code
Read information
Read name/value pair information
The entered text content is:

Passing drop-down data through a CGI program
test.html code
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title><body>
<form action="/cgi-bin/test.cgi" method="post" target="_blank">
<select name="dropdown">
<option value="runoob" selected><option value="google" Google option select>
<input type="submit" value="Submit" />form body html>test.cgi code
Read information
Read name/value pair information
The selected website is:

Using cookies in CGI
Cookie syntax
Set-cookie:name=name;expires=date;path=path;domain=domain;secure
Setting cookies
Example
Find Cookie
Example
splits on the first =.
User ID = XYZ
Password = XYZ123
CGI modules