Common Gateway Interface
Overview
CGI stands for Common Gateway Interface. CGI is the part of the Web server that can communicate with other programs running on the server. Using CGI, the server can invoke a program, while passing user-specific data to the program. User specified data supplied using HTML input form. The program then processes that data and the server passes the program’s response back to the Web browser.
Sample HTML form
We will see a simple form to calculate sum of n numbers. Save the file as .HTML file and copy it to the Apache htdocs folder.
User supplies the number from HTML form. User clicks on the button to calculate the sum. We will write a server side CGI program that calculates the sum and responds with the result.
<html> <!--HTML page to calculate sum with textbox to enter n--> Page to compute sum of n integers. Enter n on the page. <form action="http://localhost/cgi-bin/sum.cgi"> <p> Enter n: <input name="number" size=20><p> <input type="submit" value="Calculate Sum"> </form> </html>
Server Side C Program
#include <stdio.h> #include <stdlib.h> int main() { int n; int sum=0; int i; char *input = getenv(“QUERY_STRING”); sscanf(input, “number=%d”, &n); printf(“Content-type: text/html\n\n”); for(i=1; i<=n; i++) { // Calculate sum sum += i; } printf(“The sum is = %d”,sum); return 0; }
Build the project and copy the executable to Apache cgi-bin folder.
Start the Apache web server.
Visit the URL( http://localhost/sum.html )
Enter a number and click on the button.
The CGI program gets invoked and responds the result for the sum of n numbers.
Response: