C++ Web Programming
What is CGI?
- The Common Gateway Interface (CGI) is a standard that defines how information is exchanged between a web server and client-side scripts.
- The CGI specification is currently maintained by NCSA, which defines CGI as follows:
- The Common Gateway Interface (CGI) is a standard interface for connecting external gateway programs with information servers (such as HTTP servers).
- The current version is CGI/1.1, and CGI/1.2 is in progress.
Web Browsing
To better understand the concept of CGI, let's click a hyperlink to browse a specific web page or URL and see what happens.
- Your browser contacts the HTTP web server and requests a URL, i.e., a file name.
- The web server parses the URL and looks for the file name. If the requested file is found, the web server sends the file back to the browser; otherwise it sends an error message indicating you requested a wrong file.
- The web browser receives the response from the web server and displays the file or error message based on the response received.
However, for an HTTP server set up this way, whenever a file in a directory is requested, the HTTP server does not send back that file but executes it as a program and sends the program's output back to the browser for display.
The Common Gateway Interface (CGI) is the standard protocol that enables applications (called CGI programs or CGI scripts) to interact with the web server and the client. These CGI programs can be written in Python, PERL, Shell, C, or C++, among others.
CGI Architecture Diagram
The diagram below illustrates the architecture of CGI:
Web Server Configuration
Before you do CGI programming, please make sure your web server supports CGI and is configured to handle CGI programs. All CGI programs executed by the HTTP server must be in a preconfigured directory. This directory is called the CGI directory, conventionally named /var/www/cgi-bin. Although CGI files are C++ executables, by convention their extension is .cgi.
By default, the Apache web server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify another directory to run CGI scripts, you can modify the following section in the httpd.conf file:
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
Options All
Here we assume the web server is already configured and running successfully, and you can run any CGI program, such as Perl or Shell.
Your First CGI Program
Please look at the following C++ program:
Example
#include
<
iostream
using
namespace
std;
int
main
(
)
{
cout
<<
"
Content-type:text/html
\
r
\
n
\
r
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
Hello World! This is my first CGI program
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
return
0
;
}
Compile the code above, name the executable cplusplus.cgi, and save this file in the /var/www/cgi-bin directory. Before running the CGI program, please use chmod 755 cplusplus.cgi the UNIX command to change the file mode and ensure the file is executable. Accessing the executable, you will see the following output:
Hello World! This is my first CGI program
The C++ program above is a simple program that writes its output to the STDOUT file, i.e., displayed on the screen. Here, it is worth noting that the first line of output Content-type:text/html\r\n\r\n. This line is sent back to the browser and specifies the content type to be displayed in the browser window. You must understand the basic concept of CGI in order to further write more complex CGI programs using Python. C++ CGI programs can interact with any other external system (such as an RDBMS).
HTTP Header Information
line Content-type:text/html\r\n\r\n is part of the HTTP header information sent to the browser so that the page content can be better understood. The form of the HTTP header information is as follows:
HTTP 字段名称: 字段内容
例如
Content-type: text/html\r\n\r\n
There are some other important HTTP headers that you will frequently use in your CGI programming.
| Header | Description |
|---|---|
| Content-type: | MIME string defining the format of the returned file. For example, Content-type:text/html. |
| Expires: Date | information becomes an invalid date. The browser uses it to determine when a page needs to be refreshed. The format of a valid date string should be 01 Jan 1998 12:00:00 GMT. |
| Location: URL | This URL refers to the URL that should be returned, not the requested URL. You can use it to redirect a request to any file. |
| Last-modified: Date | The last modified date of the resource. |
| Content-length: N | The length of the data to be returned, in bytes. The browser uses this value to indicate the estimated download time of a file. |
| Set-Cookie: String | Pass string Set a cookie. |
CGI Environment Variables
All CGI programs can access the following environment variables. These variables play a very important role when writing CGI programs.
| Variable Name | Description |
|---|---|
| CONTENT_TYPE | the data type of the content. Used when the client sends additional content to the server, such as file upload. |
| CONTENT_LENGTH | the length of the query information. Available only for POST requests. |
| HTTP_COOKIE | returns the set cookies in the form of key & value pairs. |
| HTTP_USER_AGENT | the User-Agent request header field, which conveys information about the user's request, including the browser's name, version, and other platform-specific additional information. |
| PATH_INFO | the path of the CGI script. |
| QUERY_STRING | the URL-encoded information sent when making a request via the GET method, including the parameters after the question mark in the URL. |
| REMOTE_ADDR | the IP address of the remote host making the request. This is very useful for logging and authentication. |
| REMOTE_HOST | the fully qualified name of the host making the request. If this information is unavailable, REMOTE_ADDR can be used to obtain the IP address. |
| REQUEST_METHOD | the method used to make the request. The most common methods are GET and POST. |
| SCRIPT_FILENAME | the full path of the CGI script. |
| SCRIPT_NAME | the name of the CGI script. |
| SERVER_NAME | the host name or IP address of the server. |
| SERVER_SOFTWARE | the name and version of the software running on the server. |
The following CGI program lists all the CGI variables.
Example
#include
<
iostream
#include
<
stdlib.h
#include
<
string
using
namespace
std;
const
string
ENV
[
24
]
=
{
"
COMSPEC
"
,
"
DOCUMENT_ROOT
"
,
"
GATEWAY_INTERFACE
"
,
"
HTTP_ACCEPT
"
,
"
HTTP_ACCEPT_ENCODING
"
,
"
HTTP_ACCEPT_LANGUAGE
"
,
"
HTTP_CONNECTION
"
,
"
HTTP_HOST
"
,
"
HTTP_USER_AGENT
"
,
"
PATH
"
,
"
QUERY_STRING
"
,
"
REMOTE_ADDR
"
,
"
REMOTE_PORT
"
,
"
REQUEST_METHOD
"
,
"
REQUEST_URI
"
,
"
SCRIPT_FILENAME
"
,
"
SCRIPT_NAME
"
,
"
SERVER_ADDR
"
,
"
SERVER_ADMIN
"
,
"
SERVER_NAME
"
,
"
SERVER_PORT
"
,
"
SERVER_PROTOCOL
"
,
"
SERVER_SIGNATURE
"
,
"
SERVER_SOFTWARE
"
}
;
int
main
(
)
{
cout
<<
"
Content-type:text/html
\
r
\
n
\
r
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
"
0
\
"
cellspacing =
\
"
2
\
"
"
;
for
(
int
i
=
0
;
i
<
24
;
i
++
)
{
cout
<<
"
\
n
"
;
}
cout
<<
"
|
" << ENV [ i ] << " |
" ; // try to retrieve the value of an environment variable char value = getenv ( ENV [ i ] . c_str ( ) ) ; if ( value != 0 ) { cout << value ; } else { cout << " The environment variable does not exist. " ; } cout << " |
\
n
"
;
cout
<<
"
\
n
"
;
cout
<<
"
\
n
"
;
return
0
;
}
C++ CGI Library
In a real example, you need to perform many operations through CGI programs. Here is a CGI library written specifically for C++ programs, which we can download from ftp://ftp.gnu.org/gnu/cgicc/ to download this CGI library, and install it by following the steps below:

$ tar xzf cgicc-X.X.X.tar.gz
$ cd cgicc-X.X.X/
$ ./configure --prefix=/usr
$ make
$ make install
Note:the libcgicc.so and libcgicc.a libraries will be installed in the /usr/lib directory; you need to run the copy command:
$ sudo cp /usr/lib/libcgicc.* /usr/lib64/so that the CGI program can automatically find the libcgicc.so dynamic link library.
You can click C++ CGI Lib Documentationto view the related library documentation.
GET and POST Methods
You may have encountered a situation where you need to pass some information from the browser to the web server and finally to the CGI program. Usually the browser uses two methods to pass this information to the web server, namely the GET and POST methods.
Passing Information Using the GET Method
The GET method appends encoded user information to the page request. The page and the encoded information are separated by the ? character, as shown below:
http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2
The GET method is the default way to pass information from the browser to the web server; it generates a long string in the browser's address bar. Do not use the GET method when sending passwords or other sensitive information to the server. The GET method has a size limit: at most 1024 characters can be passed in a request string.
When using the GET method, information is passed using the QUERY_STRING http header, which can be accessed in the CGI program via the QUERY_STRING environment variable.
You can append simply concatenated key-value pairs after the URL, or use HTML