Tutorial Study Image

C++ web programming


June 15, 2023, Learn eTutorial
244

In previous C++ tutorials, you learned the fundamentals of diverse syntax and methods of constructing C++ programs for building apps and programs. This article will show you how to link your C++ software to the World wide web. You must be familiar with the fundamentals of CGI in order to accomplish this.

What do you mean by CGI?

Common Gateway Interface, or CGI, is a set of standards that specify how data is transferred from a web server, how a web user's request is forwarded to an application program, and how it is then returned to the user. Any user that requests a web page will receive it from the server. Usually, the Web server sends the form data to quick application software, which processes the information and could reply with a confirmation message. The Common Gateway Interface is a protocol or standard for exchanging data between the server and the application (CGI). It is a component of the HTTP protocol for the Web (HTTP).

Features of CGI

  • The Common Gateway Interface, sometimes known as CGI, is a collection of guidelines that specify how data is transferred between a custom script and a web server.
  • The NCSA is presently responsible for maintaining the CGI specifications, and it defines CGI as follows:
    • CGI is a standard that external gateway programs can use to connect to information servers, such as HTTP servers.
    • CGI/1.1 is the current version, and CGI/1.2 is in development.

Web Browsing

Let's examine the situation that takes place when visitors access a specific URL to explore something on the web in order to understand the concept of CGI.

  1. Your browser asks the HTTP web server for the URL and then connects.
  2. The web server will analyze the URL and look for the file name; if the requested file is located, it will be sent right away to the browser, or else an error notice will be displayed.
  3. An error message or a file received is displayed by the web browser once it receives the response from a web server.

If you're creating a website and need a CGI application to control it, you can include the application's name in the URL (uniform resource location) that your HTML code uses.

Server Configuration

Programmers should confirm that the Web server supports CGI and is set up to handle CGI applications before utilizing CGI programming. CGI files, which are C++ executables, typically have the.cgi extension. The Apache Web Server is set up by default to execute CGI applications under /var/www/cgi-bin. Any CGI application like Perl, shell, etc. must be running on a web server for programmers to use it.

C++ example of CGI program


#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 learnEtutorials </title>\n";
 cout << "</head>\n";
 cout << "<body>\n";
 cout << "<h3> <b>The Very First CGI program </b> </h2>\n";
 cout << "</body>\n";
 cout << "</html>\n";
 return 0;
}

  

 

Output:


Content-type:text/html

The Very First CGI program

  • Create an executable file from the compiled version of the preceding program, and add the.cgi extension.
  • It is necessary to keep this file in

    /var/www/cgi-bin directory

  • Additional HTTP headers that CGI programs typically employ include:

    Content type: This MIME string identifies the format of the retrieved file and describes its structure.

    Expires :Date: This specifies the day on which the information on the current web page expires.

    Location: URL: The URL that must be provided as a replacement for the one that was requested.

    Last-modified: Date: The most recent time the resource was modified.

    Content-length: N: The number indicating the data's size in bytes. The browser reports the anticipated download time using the variable "N".

    Set-Cookie: string: Cookies are set using a string that is passed through it.

Environment Variables in CGI

CONTENT LENGTH: Specifies the length, in bytes, if desired. It is only accessible through POST requests.

CONTENT TYPE: Provides the sort, or data type, of the content, if desired.

HTTP_COOKIE: If a cookie is available inside the type of key attempt, HTTP COOKIE returns the visitor's cookies.

HTTP USER AGENT: The visitor's browser type. The information about the user agent that made the request is contained in the request-header field.

PATH INFO: It offers the CGI script's trail.

REMOTE ADDR: The remote host's science address, or the science address of the visitor making the request.

REMOTE HOST: The visitor's hostname, or the host's fully qualified name, that made the request.

CGI program that lists every CGI variable.


#include <iostream>
#include <stdlib.h>
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 << "<html>\n";
   cout << "<head>\n";
   cout << "<title>CGI Environment Variables</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   cout << "<table border = \"0\" cellspacing = \"2\">";

   for ( int i = 0; i < 24; i++ ) {
      cout << "<tr><td>" << ENV[ i ] << "</td><td>";
      
      // attempt to retrieve value of environment variable
      char *value = getenv( ENV[ i ].c_str() );  
      if ( value != 0 ) {
         cout << value;                                 
      } else {
         cout << "Environment variable does not exist.";
      }
      cout << "</td></tr>\n";
   }
   
   cout << "</table><\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

 

GET and POST Methods

You must have encountered numerous circumstances when you needed to transfer data from your browser to a web server and then to a CGI program. Browsers often provide this information to web servers using two different approaches. The GET Method and POST Method are these techniques.

Using the GET Method to Pass Information

The user data is encoded and added to the page request before being sent via the GET method. The? character is used to denote a break between the page and the encoded data as shown below:

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

The GET method, which generates a lengthy string that shows in your browser's Location: box, is the standard method for transferring data between browsers and web servers. Never send a server a password or any other sensitive information via the GET method. The request string length for the GET method is limited to 1024 characters.

Information is passed using the QUERY_STRING http header when utilizing the GET method, and your CGI program can access it via the QUERY_ STRING environment variable.

Using Cookies in CGI

The HTTP protocol has no state. However, it is necessary to keep session information across various pages for a business website. For instance, one user's registration gets completed after visiting multiple pages. But how do you keep track of a user's session data throughout all of the web pages?

The most effective way to recall and keep track of preferences, sales, commissions, and other data needed for a better visitor experience or site statistics is frequently through the use of cookies.

How It Works

In the form of a cookie, your server transmits some data to the visitor's browser. The cookie may be accepted by the browser. If it does, a plain text record of it is kept on the visitor's hard drive. The cookie is now retrievable when the visitor visits another page on your website. Your server remembers/knows what was stored once it has been retrieved.

5 variable-length fields in the plain text make up a data record called "cookies."

Expires − This indicates when the cookie will expire. When a visitor closes their browser, the cookie will expire if this is left empty.

Domain – This displays the website's domain name.

Path – This displays the URL of the web page or directory that created the cookie. If you wish to obtain the cookie from any directory or page, leave this field empty.

Secure — If the term "secure" appears in this field, only a secure server may be used to retrieve the cookie. There is no such restriction if this field is left empty.

Value = Name - Key and value pairs are used to store and retrieve cookies.