YouTip LogoYouTip

Cpp Web Programming

-- Learning not just technology, but dreams! Home HTML JAVASCRIPT CSS VUE REACT PYTHON3 JAVA C C++ C# AI GO SQL LINUX VS CODE BOOTSTRAP GIT Local Bookmarks C++ Tutorial C++ Tutorial C++ Introduction C++ Environment Setup C++ Basic Syntax C++ Comments C++ Data Types C++ Variable Types C++ Variable Scope C++ Constants C++ Modifier Types C++ Storage Classes C++ Operators C++ Loops C++ Decision Making C++ Functions C++ Numbers C++ Arrays C++ Strings C++ Pointers C++ References C++ Date & Time C++ Basic Input/Output C++ Structures (struct) C++ vector Container C++ Data Structures C++ Object Oriented C++ Classes & Objects C++ Inheritance C++ Overloading Operators and Functions C++ Polymorphism C++ Data Abstraction C++ Data Encapsulation C++ Interfaces (Abstract Classes) C++ Advanced Tutorial C++ Files and Streams C++ Exception Handling C++ Dynamic Memory C++ Namespaces C++ Templates C++ Preprocessor C++ Signal Handling C++ Multithreading C++ Web Programming C++ Resource Library C++ STL Tutorial C++ Import Standard Library C++ Standard Library C++ Useful Resources C++ Examples C++ Quiz C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ C++ OpenCV C++ Multithreading C++ STL Tutorial C++ Web Programming What is CGI? Common Gateway Interface (CGI), is a set of standards that defines how information is exchanged between a web server and a client script. The CGI specification is currently maintained by the NCSA, which defines CGI as follows: Common Gateway Interface (CGI), is an interface standard for connecting external gateway programs with information servers (such as HTTP servers). The current version is CGI/1.1, and CGI/1.2 is under development. Web Browsing To better understand the concept of CGI, let's click a hyperlink, browse a specific web page or URL, and see what happens. Your browser contacts the HTTP web server and requests a URL, which is a filename. The web server parses the URL and looks for the filename. If the requested file is found, the web server sends the file back to the browser. Otherwise, it sends an error message indicating that you requested an incorrect file. The web browser receives the response from the web server and displays the file or error message based on the received response. However, with an HTTP server set up this way, whenever a file in a directory is requested, the HTTP server does not send the file itself. Instead, it executes the file as a program and sends the output generated by the execution back to the browser for display. Common Gateway Interface (CGI), is a standard protocol that enables applications (called CGI programs or CGI scripts) to interact with web servers and clients. These CGI programs can be written in Python, PERL, Shell, C, or C++. CGI Architecture Diagram The following diagram illustrates the architecture of CGI: Web Server Configuration Before you start CGI programming, ensure that your web server supports CGI and is configured to handle CGI programs. All CGI programs executed by the HTTP server must be in a pre-configured directory. This directory is called the CGI directory and is conventionally named /var/www/cgi-bin. Although CGI files are C++ executables, by convention, they have the extension .cgi. By default, the Apache web server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify a different 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 configured and running successfully, and you can run any CGI program, such as Perl or Shell. First CGI Program Look at the following C++ program: Example #include using namespace std; int main () { cout << "Content-type:text/htmlrnrn"; cout << "n"; cout << "n"; cout << "Hello World - First CGI Programn"; 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 file cplusplus.cgi, and save it in the /var/www/cgi-bin directory. Before running the CGI program, use the UNIX command chmod 755 cplusplus.cgi to change the file mode to ensure it is executable. Access the executable file, and 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, which is displayed on the screen. Here, it's worth noting that the first line of output is Content-type:text/htmlrnrn. 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 concepts of CGI to further use Python to write more complex CGI programs. C++ CGI programs can interact with any other external system (such as an RDBMS). HTTP Headers The line Content-type:text/htmlrnrn is part of the HTTP header, which is sent to the browser to better understand the page content. The HTTP header format is as follows: HTTP Field Name: Field Content For example Content-type: text/htmlrnrn There are some other important HTTP headers that are frequently used 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 Date when the information becomes invalid. The browser uses this to determine when a page needs to be refreshed. A valid date string format should be 01 Jan 1998 12:00:00 GMT. Location: URL This URL specifies 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 modification 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 Sets a cookie via the string. 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. For example, file upload functionality. CONTENT_LENGTH The length of the query information. Only available for POST requests. HTTP_COOKIE Returns the set cookies in the form of key & value pairs. HTTP_USER_AGENT User agent request header field, submitting information about the user initiating the request, including the browser name, version, and other platform-specific additional information. PATH_INFO The path of the CGI script. QUERY_STRING URL-encoded information sent when a request is made via the GET method, containing 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 not available, 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 hostname 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 CGI variables. Example #include #include #include using namespace std; const string ENV = { "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/htmlrnrn"; cout << "n"; cout << "n"; cout << "CGI Environment Variablesn"; cout << "n"; cout << "n"; cout << ""; for ( int i = 0; i < 24; i++ ) { cout << "n"; } cout << "
" << ENV << ""; // Try to retrieve the value of the environment variable char *value = getenv( ENV.c_str() ); if ( value != 0 ){ cout << value; }else{ cout << "Environment variable does not exist."; } cout << "
<n"; cout << "n"; cout << "n"; return 0; } C++ CGI Library In real-world examples, you need to perform many operations through CGI programs. Here is a CGI library written specifically for C++ programs. We can download this CGI library from ftp://ftp.gnu.org/gnu/cgicc/ and install it 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 execute the copy command: $ sudo cp /usr/lib/libcgicc.* /usr/lib64/ to allow CGI programs to automatically find the libcgicc.so dynamic link library. You can click C++ CGI Lib Documentation to view the relevant library documentation. GET and POST Methods You may have encountered situations where you need to pass some information from the browser to the web server, and finally to the CGI program. Typically, the browser uses two methods to pass this information to the web server: the GET and POST methods. Passing Information Using the GET Method The GET method sends encoded user information appended to the page request. The page and 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 method for passing information from the browser to the web server. It generates a long string of characters in the browser's address bar. Do not use the GET method when passing passwords or other sensitive information to the server. The GET method has a size limit and can pass at most 1024 characters in a request string. When using the GET method, the information is passed using the QUERY_STRING HTTP header, which can be accessed in the CGI program using the QUERY_STRING environment variable. You can pass information by appending simple key-value pairs to the URL or by using the GET method of the HTML tag. Simple URL Example: GET Method Below is a simple URL that uses the GET method to pass two values to the cpp_get.cgi program. /cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI The following example generates the cpp_get.cgi CGI program to process input from the web browser. Using the C++ CGI library, it's easy to access the passed information: Example #include #include #include #include #include #include #include #include #include using namespace std; using namespace cgicc; int main () { Cgicc formData; cout << "Content-type:text/htmlrnrn"; cout << "n"; cout << "n"; cout << "Using GET and POST Methodsn"; cout << "n"; cout << "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 << "
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 << "
n"; cout << "n"; cout << "n"; return 0; } Now, compile the program above as follows: $g++ -o cpp_get.cgi cpp_get.cpp -lcgicc Generate cpp_get.cgi, place it in the CGI directory, and try accessing it using the following link: /cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI This will produce the following result: First Name: ZARA Last Name: ALI Simple Form Example: GET Method Below is a simple example that uses an HTML form and a submit button to pass two values. We will use the same CGI script cpp_get.cgi to process the input. First Name:
Last Name: Below is the actual output of the form above. Please enter the first and last name, then click the submit button to see the result. Passing Information Using the POST Method A more reliable method to pass information to a CGI program is the POST method. This method packs the information in the same way as the GET method, but instead of passing it as a text string after the ? in the URL, it passes it as a separate message. This message is passed to the CGI script in the form of standard input. We will also use the cpp_get.cgi program to handle the POST method. Let's use the same example, passing two values using an HTML form and a submit button, but this time using the POST method instead of GET, as shown below: First Name:
Last Name: Passing Checkbox Data to a CGI Program When multiple options need to be selected, we use checkboxes. The following HTML code example is a form with two checkboxes: Maths Physics The following C++ program will generate the cpp_checkbox.cgi script to process input from the web browser via checkboxes. Example #include #include #include #include #include #include #include #include #include using namespace std; using namespace cgicc; int main () { Cgicc formData; bool maths_flag, physics_flag; cout << "Content-type:text/htmlrnrn"; cout << "n"; cout << "n"; cout << "Passing Checkbox Data to a CGI Programn"; cout << "n"; cout << "n"; maths_flag = formData.queryCheckbox("maths"); if( maths_flag ) { cout << "Maths Flag: ON " << endl; }else{ cout << "Maths Flag: OFF " << endl; } cout << "
n"; physics_flag = formData.queryCheckbox("physics"); if( physics_flag ) { cout << "Physics Flag: ON " << endl; }else{ cout << "Physics Flag: OFF " << endl; } cout << "
n"; cout << "n"; cout << "n"; return 0; } Passing Radio Button Data to a CGI Program When only one option needs to be selected, we use radio buttons. The following HTML code example is a form with two radio buttons: Maths Physics The following C++ program will generate the cpp_radiobutton.cgi script to process input from the web browser via radio buttons. Example #include #include #include #include #include #include #include #include #include using namespace std; using namespace cgicc; int main () { Cgicc formData; cout << "Content-type:text/htmlrnrn"; cout << "n"; cout << "n"; cout << "Passing Radio Button Data to a CGI Programn"; cout << "n"; cout << "n"; form_iterator fi = formData.getElement("subject"); if( !fi->isEmpty() && fi != (*formData).end()) { cout << "Radio box selected: " << **fi << endl; } cout << "
n"; cout << "n"; cout << "n"; return 0; } Passing Text Area Data to a CGI Program When multi-line text needs to be passed to a CGI program, we use the TEXTAREA element. The following HTML code example is a form with a TEXTAREA box: The following C++ program will generate the cpp_textarea.cgi script to process input from the web browser via the text area. Example #include #include #include #include #include #include #include #include #include using namespace std; using namespace cgicc; int main () { Cgicc formData; cout << "Content-type:text/htmlrnrn"; cout << "n"; cout << "n"; cout << "Passing Text Area Data to a CGI Programn"; cout << "n"; cout << "n"; form_iterator fi = formData.getElement("textcontent"); if( !fi->isEmpty() && fi != (*formData).end()) { cout << "Text Content: " << **fi << endl; } cout << "
n"; cout << "n"; cout << "n"; return 0; }
← Lua CoroutineLua Modules Packages β†’