MyPage is a personalized page based on your interests.The page is customized to help you to find content that matters you the most.

I'm not curious

CGI for Programmers

Published on 03 January 16
CGI for Programmers - Image 1
What is CGI programming?
Many confuse CGI with Computer Generated Imagery, but today we would discuss CGI that many C, Java and Perl programmers would be fond of. I’m talking about Common Gateway Interface (CGI) which is a standard platform used to generate dynamic content on Web Pages and Web applications.

The Common Gateway Interface or another term would be CGI scripts, works by providing an interface between the web server and the programs running the web content. CGI are normally written in scripting language.

That being said, here are some of the common functionalities of CGI

Functionalities of CGI

  1. CGI scripts are used to create Web documents that depend on user interaction. What it does is that CGI carry readers to random pages on the site, form pages specific to the readers based on form input, and then generate pages based on databases of information.
  2. CGI scripts are used to resolve form data such as placing the data back into the database, sending the data out as an email message and responding to the form entry with a webpage.
  3. CGI allow owners of web Servers to appoint a directory within the document collection to contain binary files or executable scripts
  4. CGI scripts are used for back door interactions with Web readers. They can set and understand cookies, collect and compile information such as browsers and operating system and calculate Web traffic hits.
  5. Lastly, the CGI system enables browsers to send information to the script through the URL or HTTP POST request. If for instance a subsequent slash directory name is appended to the URL immediately after the name of the script, the path is then stored in the PATH_INFO environment variable. If the parameters are passed to the script via a HTTP POST, then the parameters are stored in the QUERY_STRING environment variable before the script is called.
Programming Languages you can use with CGI

For those who are more in tuned with CGI scripts, the Perl language is mostly used with CGI programming. Reason is Perl has a very helpful socket support which creates CGI programs that interface smoothly with internet protocols. Your CGI program can send a webpage in response to a transaction and simultaneously send emails to inform people that a transaction happened. The Perl is also known to have flexible text handling where it can handle strings in terms of memory allocation and deallocation.

The Perl’s capable functionality is advantageous for CGI applications due to its simplistic format which allows for easy development, debugging and revision. As such, your programming task would be easier when it comes to debugging complicated compiled programs.

The following codes show the Perl program’s environment variables passed by the Web server:


printenv — a CGI program that just prints its environment

print "Content-type: text/plain\r\n\r\n";

for my $var ( sort keys %ENV ) {
printf "%s = \"%s\"\r\n", $var, $ENV{$var};

For Python Scripts, the CGI input is connected to the client, which forms data and passed the data via the query string which is part of the URL. Python also provide a number of utilities which aids in debugging scripts and support for file uploads from a form.

A few tips when using python, you may create something interesting which involves printing out a HTTP header and a Web page. Also, it is good to handle all your incoming inputs from things like HTML forms or request parameters.

To wrap it up, here is a sample code attempts to combine a simple output of a Web page with the processing of input from users viewing the page. You may wish to choose the actual first line of the script based on one of the first two lines provided below - the first one for Windows and dependent on the Python install path, whereas the second may only work on UNIX-like systems.

Code’s source:
#!C:\Python27\python.exe -u
#!/usr/bin/env python

import cgi
import cgitb; cgitb.enable() # for troubleshooting

print "Content-type: text/html"

print """

<head><title>Sample CGI Script</title></head>


<h3> Sample CGI Script </h3>

form = cgi.FieldStorage()
message = form.getvalue("message", "(no message)")

print """

<p>Previous message: %s</p>


<form method="post" action="index.cgi">
<p>message: <input type="text" name="message"/></p>


""" % cgi.escape(message)

For the Java language, writing a CGI program can be relatively easy if you know the issues. To write a Java language, you need to write the execution of the Java program inside another script. This is to allow the actual script invoked on your web server to pass a Unix shell script or a Windows batch file through the CGI environment variables into your Java program.

Another tip, the java.cgi script is a helpful method in managing interaction between the HTTP daemon and the Java CGI program. What it does is that the shell script extract names of the program that you want to run from the server provided data and collects all of the environment data into a temporary file. After which, the shell script runs the Java run-time interpreter with the name of the file of environment information and the program name added to the command-line.
Here is an example of writing a greeting form in a Java CGI program:
<TITLE&gtHello and Welcome!</TITLE>
<H1 ALIGN=CENTER&gtHello and Welcome</H1>
What is your name?
<INPUT TYPE="text" NAME="name" VALUE=""><p>
What is your email address?
<INPUT SIZE=40 TYPE="text" NAME="email" VALUE="">
<INPUT TYPE="submit" VALUE="Submit"&gt. <P>

Another compatible programming language for CGI would be JavaScript. JavaScript can be used on a web page, pass information to a CGI program after which it can return Javascript codes to the required information. You see, the CGI program itself can write JavaScript codes and assign information to JavaScript variables before it sends the code back to the web page.

Here’s a tip for JavaScript programmers: If you intend on assigning the number of files in a directory to a JavaScript variable here are the 4 steps you can take.
  1. Create a JavaScript variable to hold the number.
  2. Call the CGI program with certain information.
  3. Launch the CGI program to create and return certain JavaScript code.
  4. Print the number on the web page with JavaScript.
Once you adhere to the 4 steps, you may even form one CGI program on your server with three blocks of JavaScript.

The following sample code is an example:
NumberOfFiles = 0;


document.write('The number of files is: ' + NumberOfFiles);
C programming

For C programmers out there, you can still set up a CGI script but you have to turn it into a binary executable program. Do note however, that you need to compile and load your C program on the server.

C can be very useful for CGI programming as well due to its high speed, excellent feature set and stability.

Firstly, the processing of C programming can even be faster than PHP. Secondly, the C language offers high extensibility with its excellent feature set. Lastly, CGI programs written in C are very stable and that is because the program is compiled, it is not as susceptible to changes in the operating environment.

With the benefits of using the C language with CGI programming, here are some tips if you intend on running a CGI programme under C.
  1. Compile and test the C program in normal interactive use.
  2. Make any changes that might be needed for use as a CGI script. The program should read its input according to the intended form sub¬mis¬sion method. Using the default GETmethod, the input is to be read from the environment variable. QUERY_STRING. (The program may also read data from files—but these must then reside on the server.) It should generate output on the standard output stream (stdout) so that it starts with suitable HTTP headers. Often, the output is in HTML format.
  3. Compile and test again. In this testing phase, you might set the environment variableQUERY_STRING so that it contains the test data as it will be sent as form data. E.g., if you intend to use a form where a field named foo contains the input data, you can give the command setenv QUERY_STRING "foo=42" (when using the tcsh shell) or QUERY_STRING="foo=42" (when using the bash shell).
  4. Check that the compiled version is in a format that works on the server. This may require a recompilation. You may need to log on into the server computer (using Telnet, SSH, or some other terminal emulator) so that you can use a compiler there.
  5. Upload the compiled and loaded program, i.e. the executable binary program (and any data files needed) on the server.
  6. Set up a simple HTML document that contains a form for testing the script, etc.

Here’s an example of a set of codes, where a C program has accepted input via CGI and METHOD=POST.
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 80
#define EXTRA 5
/* 4 for field name "data", 1 for "=" */
/* 1 for added line break, 1 for trailing NUL */
#define DATAFILE "../data/data.txt"

void unencode(char *src, char *last, char *dest)
for(; src != last; src++, dest++)
if(*src == '+')
*dest = ' ';
else if(*src == '%') {
int code;
if(sscanf(src+1, "%2x", &code) != 1) code = '?';
*dest = code;
src +=2; }
*dest = *src;
*dest = '\n';
*++dest = '\0';

int main(void)
char *lenstr;
char input[MAXINPUT], data[MAXINPUT];
long len;
lenstr = getenv("CONTENT_LENGTH");
if(lenstr == NULL || sscanf(lenstr,"%ld",&len)!=1 || len > MAXLEN)
printf("<P>Error in invocation - wrong FORM probably.");
else {
FILE *f;
fgets(input, len+1, stdin);
unencode(input+EXTRA, input+len, data);
f = fopen(DATAFILE, "a");
if(f == NULL)
printf("<P>Sorry, cannot store your data.");
fputs(data, f);
printf("<P>Thank you! Your contribution has been stored.");
return 0;
With its ease of integration with many programming languages and the interactive elements it can add like add guestbooks, page counters and shopping carts to any website, CGI programming comes handy for every programmer who knows bascis of programming or html.
This blog is listed under Open Source , Development & Implementations and Networks & IT Infrastructure Community

Related Posts:
Post a Comment

Please notify me the replies via email.

  • We hope the conversations that take place on will be constructive and thought-provoking.
  • To ensure the quality of the discussion, our moderators may review/edit the comments for clarity and relevance.
  • Comments that are promotional, mean-spirited, or off-topic may be deleted per the moderators' judgment.
You may also be interested in
Awards & Accolades for MyTechLogy
Winner of
Top 100 Asia
Finalist at SiTF Awards 2014 under the category Best Social & Community Product
Finalist at HR Vendor of the Year 2015 Awards under the category Best Learning Management System
Finalist at HR Vendor of the Year 2015 Awards under the category Best Talent Management Software
Hidden Image Url