C++ Web Programming Tutorial with Examples

What is CGI?

The CGI stands for Common Gateway Interface, a set of standards describing how the web server and a custom script share information.

The NCSA is in charge of keeping the CGI specs up to date, and this is how the NCSA defines CGI:

  • The current version is CGI/1.1, and CGI/1.2 is in progress.

  • Most server root folders have a cgi-bin directory.

  • Scripts in the cgi-bin directory has file executable permissions, but files outside the directory may not.

  • A CGI script may request SERVER PROTOCOL and REMOTE HOST as input variables.

Web Browsing

To understand CGI, consider what happens when we click a hyperlink to visit a website.

  • The HTTP web server contacts the browser and requests the URL (filename). If it finds the requested file, the web server sends it to the browser; otherwise, it provides an error message.

  • The response from the web server is read by the web browser, which shows either the file that was sent or an error message.

The HTTP server may be adjusted to not send back a requested file from a specified directory.

Instead, it’s executed as a program and transmitted to your browser.

CGI is a common protocol that allows web applications to connect to Web servers and clients side.

Write CGI scripts in Python, PERL, Shell, C, or C++.

CGI Architecture Diagram

The following simple program shows a simple architecture of CGI −

CGI Architecture Diagram
CGI Architecture Diagram

Web Server Configuration

Make sure your Web Server supports CGI and setup to handle CGI Programs before starting CGI Programming.

The HTTP server executes CGI programs from a pre-configured directory. /var/www/cgi-bin. CGI files are executable but have the.cgi suffix.

First CGI Program

Consider the following C++ Program content −

#include <iostream>
using namespace std;

int main () {
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Hello World - First CGI Program</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   cout << "<h2>Hello World! This is my first CGI program</h2>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Compile the code above, and call the program that runs cplusplus.cgi.

This file is stored in the /var/www/cgi-bin directory.

Before you run your CGI program, make sure you’ve used the file using chmod 755 cplusplus.cgi UNIX command to change the mode of the file and make it executable.

HTTP Header

The line Content-type:text/htmlrnrn is part of the HTTP header that is delivered to the browser in order to interpret the content.

Each HTTP header will be formatted as follows:

HTTP Field Name: Field Content

For Example
Content-type: text/html\r\n\r\n

CGI Environment Variables

All CGI programs will have access to the environment variables listed below.

These factors play an important part in the development of every CGI software.

Variable NameDescription
CONTENT_TYPEThe content’s data type is utilized when the client sends associated material to the server. For example, file upload etc.
CONTENT_LENGTHThe size of the query information is limited to POST requests.
HTTP_COOKIEReturns the specified cookies as a key-value pair.
HTTP_USER_AGENTThe User-Agent request-header field specifies the user agent that initiated the request. It is the title of a web browser.
PATH_INFOThe directory of the CGI script.
REMOTE_ADDRThe IP address of the requesting host. This is helpful for logging and authentication.
REMOTE_HOSTThe fully qualified hostname of the requesting host. If this information is unavailable, the REMOTE ADDR variable may be utilized to determine the IR address.
SCRIPT_FILENAMEThe full path to the CGI script.
SCRIPT_NAMEThe name of the CGI script.

C++ CGI Library

There is a CGI library written for C++ program, which you can download from ftp://ftp.gnu.org/gnu/cgicc/ and follow the steps to install the library whenever you would need to do many operations with your CGI program.

You can check related documentation available at ‘C++ CGI Lib Documentation.

GET and POST Methods

The Get and POST methods are browser methods used to pass information to the web servers.

This is what you need to send information from your browser to your web server and then to your CGI program many times.

Passing Information Using GET Method

The GET method transmits encoded user data added to a page request.

The ? character separates the encoded information from the page as shown:

http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2

The GET method is the normal technique for passing information between a browser and a web server, and it generates a lengthy string that displays in the Location:box of your browser.

Never utilize the GET method when passing a password or other sensitive data to a server.

The GET method has a maximum length restriction of 1024 characters for the request string.

Simple URL Example: Get Method

Here is a simple URL that will pass two values to the hello_get.py program using the GET method ./cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI.

Below is a program to generate cpp_get.cgi CGI program to handle input given by the web browser.

We will use the C++ CGI library, which makes it very easy to access passed information.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>  

using namespace std;
using namespace cgicc;

int main () {
   Cgicc formData;
   
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Using GET and POST Methods</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("first_name");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "First name: " << **fi << endl;  
   } else {
      cout << "No text entered for first name" << endl;  
   }
   
   cout << "<br/>\n";
   fi = formData.getElement("last_name");  
   if( !fi->isEmpty() &&fi != (*formData).end()) {  
      cout << "Last name: " << **fi << endl;  
   } else {
      cout << "No text entered for last name" << endl;  
   }
   
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Simple FORM Example: GET Method

Here is a simple example that passes two values using HTML FORM and submits the button.

We are going to use the same CGI script cpp_get.cgi to handle this input.

<form action = "/cgi-bin/cpp_get.cgi" method = "get">
   First Name: <input type = "text" name = "first_name">  <br />
 
   Last Name: <input type = "text" name = "last_name" />
   <input type = "submit" value = "Submit" />
</form>

Passing Information Using POST Method

The POST method is a more reliable method of passing information to a CGI program.

This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after ? in the URL, it sends it as a separate message.

This message comes into the CGI script in the form of the standard input.

The same cpp_get.cgi program will handle POST method as well.

Let us take the same example as above, which passes two values using HTML FORM and submit button but this time with POST method.

<form action = "/cgi-bin/cpp_get.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>

Passing Checkbox Data to CGI Program

Checkboxes are used when many options must be chosen.

Here is an example HTML code for a form with two checkboxes −

<form action = "/cgi-bin/cpp_checkbox.cgi" method = "POST" target = "_blank">
   <input type = "checkbox" name = "maths" value = "on" /> Maths
   <input type = "checkbox" name = "physics" value = "on" /> Physics
   <input type = "submit" value = "Select Subject" />
</form>

Passing Radio Button Data to CGI Program

Radio buttons are used when just one choice must be selected.

Example HTML code for two radio buttons.

<form action = "/cgi-bin/cpp_radiobutton.cgi" method = "post" target = "_blank">
   <input type = "radio" name = "subject" value = "maths" checked = "checked"/> Maths 
   <input type = "radio" name = "subject" value = "physics" /> Physics
   <input type = "submit" value = "Select Subject" />
</form>

Passing Text Area Data to CGI Program

Text Area element is used when multiline text needs to be given to the CGI Program.

Example HTML code for TEXTAREA:

<form action = "/cgi-bin/cpp_textarea.cgi" method = "post" target = "_blank">
   <textarea name = "textcontent" cols = "40" rows = "4">
      Type your text here...
   </textarea>
   <input type = "submit" value = "Submit" />
</form>

Passing Dropdown Box Data to CGI Program

A drop-down box is used when there are many choices, but only one or two will be chosen.

Example HTML code for Dropdown:

<form action = "/cgi-bin/cpp_dropdown.cgi" method = "post" target = "_blank">
   <select name = "dropdown">
      <option value = "Maths" selected>Maths</option>
      <option value = "Physics">Physics</option>
   </select>
   
   <input type = "submit" value = "Submit"/>
</form>

Using Cookies in CGI

Using cookies is often the best way to remember and track preferences, purchases, commissions, and other information that is needed to make the visitor experience better or to get better site statistics.

How It Works

The visitor’s browser receives a cookie from your server. A cookie may be accepted.

If so, it’s kept on the visitor’s hard disk as plain text. The cookie is now retrievable when the visitor visits another page.

Your server side remembers what’s saved once retrieved.

Cookies are a plain text data record of 5 variable-length fields −

  • Expires − The cookie’s expiration date. If blank, the cookie expires when the visitor closes the browser.

  • Domain − This displays your website’s domain.

  • Path − This indicates the directory or web page from which the cookie was set. This may be left blank if the cookie is to be retrieved from any directory or page.

  • Secure − If this field includes the term “secure,” only a secure server may obtain the cookie. If this field is empty, there is no such limitation.

  • Name = Value −Setting and retrieving cookies involves key-value pairs.

Setting up Cookies

It is really simple to transmit cookies to a browser.

These cookies will be sent with the HTTP header to the Content-type field.

I am assuming that you want to save UserID and Password as cookies. Therefore, configured cookies are as follows.

#include <iostream>
using namespace std;

int main () {
   cout << "Set-Cookie:UserID = XYZ;\r\n";
   cout << "Set-Cookie:Password = XYZ123;\r\n";
   cout << "Set-Cookie:Domain = www.itsourcecode.com;\r\n";
   cout << "Set-Cookie:Path = /perl;\n";
   cout << "Content-type:text/html\r\n\r\n";

   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Cookies in CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   cout << "Setting cookies" << endl;  
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Retrieving Cookies

It is simple to retrieve all set cookies.

The CGI environment variable HTTP COOKIE kept Cookies, which looks like this.

key1 = value1; key2 = value2; key3 = value3....

Conclusion

In summary, the main focus of this session was to learn a C++ Web Programming Tutorial with Examples and get deeper into what CGI or common Gateway Interface is and how to connect the web to a C++ program in a new way.

This part is vital to our understanding of the C++ Programming language.

That’s it! What is a C++ Web Programming Tutorial with Examples is now complete! 

Leave a Comment