adapted from http://www.cs.utk.edu/~cs460.is&r/cgi-c.html
It gives some basics about how to write CGI using C.
CGI applications can be written in any language that can be executed
on a Web platform such as: C/C++, Perl, Tcl, Python, Shell
Scripts(UNIX), Visual Basic and Applescript. Your choice depends on
what you have to do because different languages may be specialized
for different purposes. Perl, for instance, is great for string and
file manipulation, while C is better for bigger, more complex
programs. Perl and C are probably the most used languages for CGI
programming.
We all know how CGI interacts with Perl. In Perl, we used
$queryString = $ENV to access the environmental
variable. In C, you could call the library function "getenv()", which is defined in standard library .
Here is a simple example of how to call this function:
Sample source C code (search.c):
#include <stdio.h> #include <stdlib.h>
int main(void) { char* query;
printf("%s%c%cn","Content-Type:text/html;charset=iso-8859-1",13,10); printf("<title>Search Result</title>n"); printf("<H3>Search Result</H3>n");
query = getenv("QUERY_STRING");
// Note 1: other functions to truncate the query string
// Note 2: other functions to search for the related documents
// Now, if you find the word and want to display on user's browser, do
printf("n<p> word %s is foundn", query); }
Note 1: remember the string returned by getenv() is in a format:
"key=academic+research&send=search" (assume the user types in
"academic research". So you need to do some truncation work to obtain
the actual query string.
Note 2: your code to search for the related docs for a specific
term.
Then compile the C code as you normally do:
gcc -o search.cgi search.c
Be careful to name your C executable as *.cgi or it will not work
on web.
In your form.html:
<FORM ACTION="http://www.cs.utk.edu/~xyz/cgi-bin/search.cgi" METHOD="GET"> <p> Enter your key word separated by blank: <INPUT TYPE="text" NAME ="key" SIZE =60 MAXLENGTH=200> <INPUT TYPE ="Submit" NAME ="send" VALUE="Search"> <INPUT TYPE="Reset" NAME ="clear" VALUE="Reset"> </FORM>
Additional information on this subject could be found in:
http://www.hut.fi/u/jkorpela/forms/cgic.html
Also there is a nice cgi-c package which can be found in
http://www.boutell.com/cgic/#obtain. They provide more
sophisticated library functions than <stdlib.h>.
Written by Kathy Xiayoyan Zhang, April 1999.
|