COMMON GATEWAY INTERFACE (CGI)

CGI is the part of the Web server that can communicate with other programs running on the server. With CGI, the Web server can call up a program, while passing user-specific data to the program (such as what host the user is connecting from, or input the user has supplied using HTML form syntax). The program then processes that data and the server passes the program’s response back to the Web browser.

The output of a C++ program can be obtained on a web browser using CGI via following methods:

1.without a script 2.with a script

WITHOUT SCRIPT

Here is C++ program that need to be placed in cgi-bin folder. (albert.cc)

#include <iostream>
using namespace std;
int main(void)
{
cout<<"Content-type: text/html";
cout<<endl<<endl ;
cout << "Hello this is my first ever CGI program " << endl ;
return 0;
}

RUN THE PROGRAM

#sudo -s
#cd /usr/lib/cgi-bin
#g++ albert.cc

This will create an executable file a.out.

Now open the browser and type in the URL http://localhost/cgi-bin/a.out

WITH SCRIPT

Here is C++ Code: (albert.cc)

#include <iostream>
using namespace std;
int main(void)
{
cout << " my first ever CGI program " << endl ;
return 0;
}

HERE IS SCRIPT(albert)

#!/bin/sh
echo Content-type: text/html
echo
echo "<pre>" ./a.out echo "</pre>"

Place both C++ program and script in /usr/lib/cgi-bin folder.

CODE EXECUTION

Go to terminal.Type

$sudo -s
#cd /usr/lib/cgi-bin
#g++ albert.cc
#firefox http://localhost/cgi-bin/albert

And you will get output of C++ on browser.

ACCESSING FORM INPUT

For this we need an html form also, which takes input from user.

Here is Html code: (alberta.html)
<body bgcolor = #d0e4fe>
<form action="http://localhost/cgi-bin/albert" method="GET">
<font color = red size = 6> <center></font><br/><br/><br/> ENTER YOUR AGE: <input type="text" name="fn"/>
<input type="submit" value = "Submit" /></center>
</form>

Here is the C++ program(alberta.cc)

#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
main(int argc, char **argv )
{
int fn = atoi ( argv[1] );
cout<<"<html><head><title> Vote for AAP!! </title></head><body bgcolor = #d0e4fe>";
if(fn<18)
cout<<"<h1><center>you cannot Vote</center></h1><br><h2>Wait for "<<18-fn<<" years</h2>";
else
cout<<"<h1><center>you can vote!!!</center></h1><br></body></html>";
return 0;
}

Here is the script(alberta)
#!/bin/sh
echo Content-type: text/html
echo
echo '<html> <head> <title> CGI script </title> </head> <body>'
fn=`echo "$QUERY_STRING" | sed "s|fn=||"`
echo "<pre>"
./a.out "$fn"
echo "</pre>"

EXECUTION
Place C++ program and script in /usr/lib/cgi-bin and html program in /var/www

Go to terminal:

$sudo -s
#cd /usr/lib/cgi-bin
#g++ alberta.cc
#firefox http://localhost/alberta.html

Give the value in form and press submit button. Script will run and give the output on browser using html

Advertisements