Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

CGI Programming in C++


  • Please log in to reply
2 replies to this topic

#1 mdebnath


    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 09 November 2012 - 10:01 AM

The article shall demonstrate how to write your first CGI program in C++. Most of the code used in the article are given in full with output. Care has been taken so that readers may go hands on while going through the article. Links and references are provided regarding softwares/tools to download and external documentation/manual to peruse where ever deemed fit in the article. Happy learning :)

About CGI
Common Gateway Interface (CGI) is a standard protocol that enable programs to interact with the Web Servers and with clients through browsers. CGI is mainly used to generate dynamic web content using client input, database and other information services. Dynamic web content means the content is generated programmatically on request. CGI is not specific to any particular operating system or to any one programming language. It is designed to be used with virtually any programming language such as C, C++, Perl, Python or Visual Basic.

Simple HTTP Transactions
When the browser sends an HTTP request to the server the GET method indicates that the client sends a get request and wishes to retrieve a resource. Any server that understands HTTP will be able to translate this request and respond appropriately.



Software Requirements
Apart from C++ compiler and any preferred IDE, download: Web Server: Apache HTTP Server and install the binary file or extract the zipped archive in any preferred location. Consult the documentation of appropriate version installation, configure and how to start, stop the server. Once installed and configured and started the server properly, to check if service is up and running as expected, open the browser and provide the URL: http://localhost. This will open the test page as follows:


That's it your are done. Lastly, check the installation directory: “.../<installation_directory>/www/” the structure should be more or less as follows.


CGI programming
CGI programming in C++ is as simple as your old fashioned CUI programming. Before getting our hands dirty lets clarify a little of some concepts. You must be aware of the cout statements, until now in a common C++ program the output of cout always has been displayed on the screen. This is alright, because the default target for cout is standard output. But when C++ program is executed as a CGI script, the standard output is redirected by the Web Server to the client web browser. To execute the program as a CGI script, place the compiled C++ executable file in the Web Server's cgi-bin directory. Change the executable file extension from .exe to .cgi. However note that on a server running Microsoft Windows, the executable may be run directly in .exe form and in case of Linux file extension is immaterial. Now assuming that the Web Server is on your local computer, you can execute the script by typing:

http://localhost/cgi-bin/myprog.cgi (where myprog.cgi is your actually myprog.exe)

in your browser' Address or Location field. If your are requesting CGI script from a remote Web Server, simply replace the localhost with the server's machine name or IP address.

First CGI program
Lets try a very basic program to check whether we have grasped the concept and go hands on with the simple programs.

C++ Code
#include <iostream>
#include <ctime>

using namespace std;

int main()
time_t now;
cout << "Content-Type: text/html\n\n";

cout << "<?xml version = \"1.0\"?>"
<< "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" "
<< "\"[url="http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\%22>%22;"]http://www.w3.org/TR...html11.dtd\">";[/url]

time( &now );

cout << "<html xmlns = \"[url="http://www.w3.org/1999/xhtml\%22>"]http://www.w3.org/19.../1999/xhtml\">"[/url]
<< "<head><title>My First Program</title></head>"
<< "<body>"
<< "<h1>My First CGI Program</h1>"
<< "<p>Current Date and Time is" << asctime( localtime( &now ) )<<"</p>"
<< "</body></html>";
return 0;

Compile this code and copy the executable file in cgi-bin directory. Start the Web Server and type the appropriate url in the Address or Location field to summon CGI script.

Sending Input to a CGI Script
Let's try a program where user input will be captured through HTML page which on submit would call the CGI script. Save the HTML file in html directory of the Web server and compiled C++ code in the cgi-bin directory. Note that the C++ executable file is renamed with .cgi (greet.cgi in this case) extension.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "[url="http://www.w3.org/TR/html4/loose.dtd%22>"]http://www.w3.org/TR...ml4/loose.dtd">[/url]
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<form method = "post" action = "/cgi-bin/greet.cgi">
<p>Enter your name</p>
<input type = "text" name = "name">
<input type = "submit" name = "button"/>

C++ Code
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main()
char query[1024];
int len, startNumberLocation, endNumberLocation;
string data;
char strnum[20];
len = atoi(getenv("CONTENT_LENGTH"));
cin.read(query, len);
data = query;
startNumberLocation = data.find("number")+6;
endNumberLocation = data.find("&button");

cout << "Content-Type: text/html\n\n";
cout << "<?xml version = \"1.0\"?>"
<< "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" "
<< "\"[url="http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\%22>%22;"]http://www.w3.org/TR...html11.dtd\">";[/url]
cout << "<html xmlns = \"[url="http://www.w3.org/1999/xhtml\%22>"]http://www.w3.org/19.../1999/xhtml\">"[/url]
<< "<head><title>Welcome message</title></head>"
<< "<body>"
<< "<h1>Greetings!</h1>"
<< "<p>Welcome " << (data.substr(startNumberLocation, endNumberLocation-startNumberLocation)) <<"</p>"
<< "</body></html>";
return 0;



Programming CGI in C++ can be fun but it is also very cumbersome. You have to write a lot of boilerplate code. However, there are some third party libraries to make life easy such as GNU Cgicc, Wt C++ Web Toolkit. These libraries provide a lot of features apart from making CGI programming in C++ easy. Nonetheless, without any external libraries also you can write CGI program. This article provides a starting point, once you set your foot there is much to explore.

  • 2

#2 Sato


    CC Lurker

  • New Member
  • Pip
  • 9 posts
  • Programming Language:C, PHP, PL/SQL
  • Learning:Java

Posted 22 November 2012 - 10:52 PM

Nice share but I recommend adding some examples of CGI applications and implementations. But anyways, great article and thanks for the share!
  • 0

#3 Orjan


    CC Mentor

  • Moderator
  • 2918 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#

Posted 22 November 2012 - 11:39 PM

I don't understand why you send the <xml> tag, it's only supposed to be thee if you have a xml file, not in html, which just starts with the doctype.

One thing which is important to tell about programming CGI is that when starting your output, you are outputting http header information. The Content type is the least what you need to send as a header:

Content-Type: text/html

If you're done with the header, you need to make two endlines (\n\n), one to end the line and the second one to end the header information. Then you can start sending the body.
  • 0

I'm a System developer at XLENT Consultant Group mainly working with SugarCRM.
Please DO NOT send mail or PM to me with programming questions, post them in the appropriate forum instead, where I and others can answer you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download