Dr. Mark Humphrys

School of Computing. Dublin City University.

Online coding site: Ancient Brain

coders   JavaScript worlds

Search:

Free AI exercises


CGI scripts

CGI (Common Gateway Interface)
This is the oldest way to put a program on the Web that remote clients can send input to.
Any program in a special directory (normally cgi-bin) can be addressed over the Web.
CGI is language independent.



Use PHP instead

CGI is less used now.
Dedicated server-side solutions integrated with the web server (like PHP) are preferred, rather than a directory of standalone programs.

I do the introduction to HTML Forms and server-side programs with PHP:

That is the best introduction to this topic. This page remains in case you do need a CGI solution.
  


Example CGI script

We need a HTML Form on the client and a program in cgi-bin on the server.

  

HTML Form

Embed something like this HTML Form in your page. The input field name here is "q".


<FORM METHOD="GET" ACTION="https://SERVER/cgi-bin/USER/PROGRAM">
<b> Enter argument: </b> 
<INPUT size=40 name=q id=q >
<INPUT TYPE="submit" VALUE="Submit">
</FORM>


CGI script

The CGI program is put in a special directory called something like /cgi-bin.

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
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.


CGI script in Shell

The CGI script can be written in any language. Here is one 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>"


The same issues with Security of user input need to be taken care of.

  

Working example

There is no working example of the above. I am not using cgi-bin on our server any more.





ancientbrain.com      w2mind.org      humphrysfamilytree.com

On the Internet since 1987.      New 250 G VPS server.

Note: Links on this site to user-generated content like Wikipedia are highlighted in red as possibly unreliable. My view is that such links are highly useful but flawed.