cgi and c++
Overview
This section describes the creation of CGI scripts in the C++ programming language. You should have prior knowledge of ANSI C++ before continuing. A number of excellent resources can be found in our CGI Links section.
That said, let’s get down to the nitty-gritty CGI internals! Making CGI scripts is actually quite simple if you know your way around C++. The server automatically takes whatever your program outputs to stdout and redirects it to the browser. So, for instance, if you wanted to send the text “Hello, World!” to the browser, you would simply state:
cout << "Hello, World!";
Easy, huh? Well, there are a few more things that have to be done…
The content-type header
Every CGI script must first output a content-type header that specifies the MIME type of the data that is being output by the script - for instance, text/plain if it is outputting plaintext, or text/html if it is outputting an HTML webpage.
The actual code for this header looks like this:
cout << "Content-type: text/plain" << endl << endl;
Note the two newlines following the header: this tells the server where the headers end and where the data begins.
Your first cgi script
Armed with this knowledge, we can create our first functional CGI script:
#include <iostream.h>
void main()
{
cout << "Content-type: text/plain" << endl << endl
<< "Hello, World!";
}
Yes, believe it or not, this is a real, bona fide CGI script, even though it doesn’t do much. All it does, in fact, is sends the text “Hello, World!” to the browser.
Now, let’s spruce it up. Say we want to output not just “Hello, World!” in text, but why not make it pretty with some HTML formatting?
#include <iostream.h>
void main()
{
cout << "Content-type: text/html" << endl << endl
<< "<html>" << endl
<< "<head>" << endl
<< "<title>CGI Test” << endl
<< “” << endl
<< “<body>” << endl
<< “<h1><em>” << endl
<< “Hello, World!” << endl
<< “
” << endl
<< “