School of Computing. Dublin City University.
The classic example would be a search engine.
A search box in a web page is implemented as a HTML Form in the HTML code for the page.
This passes its input to the remote CGI script for processing.
The CGI script displays its output as another, new web page.
<FORM METHOD="GET" ACTION="http://computing.dcu.ie/cgi-bin/humphrys/demo/min-cgi-script"> <b> Enter argument: </b> <INPUT size=40 name=q VALUE=""> <INPUT TYPE="submit" VALUE="Submit"> <INPUT TYPE="reset" VALUE="Reset"> </FORM>
The script will go in something like:
Your path for where to put the script may vary.
The input comes in as the environment variable QUERY_STRING.
If there is a single argument, QUERY_STRING will be of the form: fieldname=actualargument
So we need to edit it to remove the fieldname= bit at the front.
The CGI script builds a web page dynamically, by outputting HTML tags to stdout. (In fact, the CGI script could output something other than a web page, e.g. an image. It tells the client what is coming using the Content-Type: HTTP header and a MIME type.)
The CGI script can be written in any language. I'll be writing it here in UNIX Shell.
#!/bin/sh echo "Content-type: text/html" echo echo '<html> <head> <title> CGI script </title> </head> <body>' argument=`echo "$QUERY_STRING" | sed "s|q=||"` echo " QUERY_STRING is: <b> $QUERY_STRING </b> <br>" echo "Actual argument is: <b> $argument </b> <br>"
Remember that anyone may send any input whatsoever to your CGI script, including attempts to run commands on your system or attempts to upload spam.
Even echoing in a shell script (as above) may not be safe, since echo recognises some switches and special characters.
The safest thing to do (and what I do in fact on this server, though I don't show it to you) is to do some security pre-processing (I use C++) to check the input character by character, before proceeding with safe and checked input.
We could write the CGI script in C++, somehow combining it with our program source code. Or we could keep the Shell script as a wrapper, and make the last line of it:
where our C++ program writes HTML tags to stdout.prog "$argument"
where the C++ program just writes its usual output to stdout.echo "<pre>" prog "$argument" echo "</pre>"