SoFunction
Updated on 2025-04-12

A good CGI script (script)

Learn CGI scripts(script)CGI means Common Gateway Interface, a method of program that runs on a web server based on browser input. CGI scripts enable your browser to interact with users, to find a noun in the database, provide comments you wrote, or select several entries from a form and get a clear answer. If you have ever encountered filling out forms or searching on the web, you are using CGI scripts. You may not realize that at that time, because most of the work is running on the server, and all you see is the result.

As a web designer, you create a client's CGI script, which is used by the server-side program to process user input, and the result is returned to the user.

Here you will learn everything about CGI scripts:

  • What is a CGI script? How it works
  • What does a CGI script output look like?
  • How to create a CGI script with parameters or without parameters
  • How to create a CGI script that returns a specified response
  • How to create a CGI script for input form
  • Questions about using CGI scripts
  • CGI variables that you can use in scripts

This chapter assumes that it is under the UNIX system.

What is a CGI script?

A CGI script is simply a program running on a web server, triggered by the browser's input. This script is usually like a bridge between the server and other programs in the system such as databases.

Are CGI scripts not a real script? According to your server's support, they may be a compiled program or batch command file or other executable stuff. For simplicity, we collectively call them scripts.


A CGI script is any program that runs on a web server. CGI means Common Gateway Interface.  

CGI scripts are used in two ways: ACTION as a form or as a direct link in a page.

How do CGI scripts work?

CGI scripts have server calls, which are based on browser data input. Figure 1 shows what a process is between the browser, server and script.

Figure 1. From browser to server to script to programRemember to come back!

Here is a brief explanation:

  1. A URL points to a CGI script. The URL of a CGI script can appear anywhere like a normal URL.
  2. When the server receives the request, executes the script according to the script file pointed to by that URL (note the location and extension of the file).
  3. The script performs operations based on input data, including querying the database, calculating numerical values, or calling other programs in the system.
  4. The script produces some kind of output that the web server can understand.
  5. The server receives the output from the script and passes it back to the browser to let the user know the result.
 

A simple example

Here we explain all the details about the occurrence step by step.
In Figure 2, there is an example diagram:
Figure 2. Page with a script connection.

At Display Date is a connection to a CGI script. Its HTML is as follows:

<A HREF="/cgi-bin/getdate">Display the Date</A>
It means that it is a CGI script because there is a cgi-bin path. On many servers, cgi-bin is a directory that can only place CGI scripts.

When you select this connection, your browser will make a request to the server. The server receives this request and calculates the script file name at the URL and executes the script.

This getdate script is executed in UNIX system like this:

#!/bin/sh


echo Content-type: text/plain


echo


/bin/date
The first line is a special command that tells the UNIX system that this is a shell script; the real situation is that the next line starting from this line, this script does two things: it outputs the line Content-type: text/plain, and then starts a blank line; second, it calls the UNIX system time date program, so that the date and time are output. After the script is executed, the output should be like this:
Content-type: text/plain


Tue Oct 25 16:15:57 EDT 1994
What is this Content-type? It is a special encoding, and the web server uses to tell the browser to output the type of text. This is the same as the Content-type meaning in HTML.

This way the browser output is as shown in Figure 3.

Figure 3 date script output result.

This is the most basic, the actual situation is much more complicated, and it can be used to understand how browsers, servers and scripts work.

Can I use CGI scripts?

Before you use CGI scripts, there are two things you might want to solve: CGI scripts are advanced web features and require as good knowledge as web server managers.

Sure? You just can't do it, can you learn? All right! Let's continue.

Does your server configuration allow CGI scripts?

In order to be able to write and run CGI scripts, you need a web server. Unlike the usual HTML files, you cannot write or experiment with your CGI scripts on the local system; you have to do this through the web server.

But even if you have a web server, this server must be configured specifically for running CGI scripts. That means all your scripts must be placed in a directory called cgi-bin.

Before writing a CGI script, ask your server administrator if you allow you to install and run CGI scripts, and where do they have to place them if they can? Also, you must have a real web server. If it is an FTP or Gopher server, then you cannot use CGI.

If you run on your own server, you must create a directory called cgi-bin and configure your server to recognize this directory as a script directory. You must also remember the following features of CGI scripts:

  • Each script is a program, which runs on a system that the browser can request, and uses CPU time and memory when executing. What happens if thousands of these scripts run at the same time? Your system will not bear the load until it crashes.
  • If you don't write your CGI script carefully, you will have the potential to let others enter the system that hurts you through your CGI script parameters.

Can you program?

Beginners should pay attention! Generally, you must have some basic programming concepts and methods. You must have experience working in similar systems. If you don't have these backgrounds, you have to study, okay, I won't say much.

What programming language do you have to use?

You can write CGI scripts in any language you are familiar with, as long as your script follows the rules shown in the next section, as long as that language can run on your web server system.

In this study manual, CGI scripts are written in only two languages: UNIX shell and Perl. This shell is suitable for running on any similar UNIX system and is easy to learn, but it is difficult to deal with complex situations. Perl, it is time to use this language, it is free, this language is stable and powerful, similar to C, but it is also difficult to learn.

Is your server setup correct?

In order to run any CGI script, whether simple or complex, your server must be set up to be able to run them, must be placed in a specific directory, and must have a file extension that depends on your server's settings.

If you are renting a server, you must allow CGI scripts to be run.

If you have your own server, check how your server manual handles CGI scripts.

What if you are not using UNIX?

I had to find another study manual.

Dissect a CGI script

If you have written it for a long time and overcome many warnings and configurations, congratulations, you already know some CGI scripts and can be used on your web page. In this chapter, you will learn how scripts are executed and how your server responds to conversations with them.

Output header

Although your CGI script allows you to do anything, the output of the script must still have a prescribed form.

This "script output" means data sent back to the server by your script. In UNIX systems, the output is sent to standard output, where the server detects it. On other systems and servers, your script output may be different.

This header is actually not part of the text, but an information protocol between the server and the browser, you can't actually see it.

There are three types of headers: Content-type, Location, and Status. Content-type is the most common.

For an explanation of content-type, see the instructions for HTML, a specific encoding you can issue like this:

Content-type: text/html
In this example, the output data type is text/html; in other words, it is an HTML file.
    Table 1. General formats and content-types.
 
Format
Content-Type
HTML text/html
Text text/plain
GIF image/gif
JPEG image/jpeg
PostScript application/postscript
MPEG video/mpeg
Note that content-type must be followed by a blank line. If you don't have a blank line, the server will not be able to figure out where the header ends.

Output data

The data you output should comply with the content-type you specified; if the content-type is text/html, the output should be placed in HTML. If the content-type is image/gif, the output should be in a binary GIF file.
Exercise 1: Try it.
T This is a simple script that outputs dates. This CGI script also checks if I have logged into my web server and reports what I found (as shown in Figure 4).

Figure 4. The script results
This is a very simple example, he can prepare the call like this:

<A HREF="/cgi-bin/pinglaura">Is Laura Logged in?</A>
This is a script without input, it only runs and returns data.

According to the previous explanation, the content of this script is as follows:
#!/bin/sh
 

echo Content-type: text/html
 

echo "<HTML><HEAD>"
 

echo "<TITLE>Is Laura There?</TITLE>"
 

echo "</HEAD><BODY>"
To test if I have logged into the system, use the who command (my login name is assumed to be lemay), and store the result in the variable ION. If I log in, the variable ION will have something, otherwise it will be empty.

ison='who | grep lemay'
The test results and scripts that return the corresponding prompts are as follows:
if [ ! -z "$ison" ]; then


        echo "<P>Laura is logged in."</P>


else


        echo "<P>Laura isn't logged in."</P>


fi
Finally close HTML:
echo "</BODY></HTML>"
Now you run him from the command line and test it, you will get a result saying that I am not logged into your system, of course it is impossible, and his output is like this:
Content-type: text/html


<HTML><HEAD>


<TITLE>Are You There?</TITLE>


</HEAD><BODY>


<P>Laura is not logged in.


</BODY></HTML>
This is an HTML text output so that your browser can display it normally because it is an HTML file.


 


Now copy it to the cgi-bin directory of your server and execute it. If you cannot reach the CGI-bin directory, you must ask your server administrator. You cannot set up a CGI-bin directory for granted, that is useless.

The complete script for this example is as follows:

#!/bin/sh

echo "Content-type: text/html"


echo

echo "<HTML><HEAD>"

echo "<TITLE>Is Laura There?</TITLE>"

echo "</HEAD><BODY>"

ison='who | grep lemay'

if [ ! -z "$ison" ]; then

        echo "<P>Laura is logged in"

else

        echo "<P>Laura isn't logged in"

fi

echo "</BODY></HTML>"

Script with parameters

In order to pass a parameter to the script, you can use (?) to insert the script noun and parameter in the URL, and use the plus sign (+) to represent each single parameter, such as:
<A HREF="/cgi-bin/myscript?arg1+arg2+arg3">run my script</A>
When the server receives this request, it passes the arg1, arg2, and arg3 parameters to the script. You can then use these parameters in the script.

This method is sometimes called query, because it was used in the search function in the early days.

Exercise 2: Check if anyone logs in.
Since you know how to use parameters, let's continue with the example above pinglaura. By modifying this example, we get the following script pinggeneric.

Let's take a different question:

#!/bin/sh


echo "Content-type: text/html"


echo


echo "<HTML><HEAD>"


echo "<TITLE>Are You There?</TITLE>"


echo "</HEAD><BODY>"
In the example above, the next step should be to test whether I log in, here we use the parameter ${1} instead of my name lemay, ${1} as the first parameter, ${2} as the second, and ${3} as the third.
ison='who | grep "${1}"'


All the remaining modifications are as follows:

if [ ! -z "$ison" ]; then


        echo "<P>$1 is logged in"


else


        echo "<P>$1 isn't logged in"


fi
echo "</BODY></HTML>"
OK, let's modify the connection in the HTML page! So that's it:
<A HREF="/cgi-bin/pinglaura">Is Laura Logged in?</A>
After modifying it to a general query function, such as querying whether a person named john logs in:
<A HREF="/cgi-bin/pinggeneric?john">Is John Logged in?</A>
Try it on your server to see if there are any results.

Pass other information to the script

There is a second way to pass information to a CGI script. It is called path information and is used as parameters that are not changed in script calls, like a temporary file name or the file name of the call script itself. As you can see, the parameters after the question mark in the example above are changed due to input to the user form. Path info is used as other information to pass to the script, and in fact, you can use it to do anything.

Path information Path information is a method that does not pass information frequently like usual parameter scripts. Path information usually refers to files such as configuration files, temporary files, or files called by scripts due to problems, etc. on the web server.  

See the following path information example,:

http://myhost/cgi-bin/myscript/remaining_path_info?arg1+arg2
When the script is running, the information in the path will be placed in the environment parameter PATH_INFO. You can use this information in your script content.

For example, let's assume that you already have multiple connections to the same script on multiple pages. You can use this path information to display the name of the connected HTML file. In this way, after you finish processing your script, when you send back an HTML file, you can include a connection in the file and send back the user's initial page.

You will learn more path information in the next chapter: useful forms and scripts. Please log out later

Create a special script output

Now you have learned how to send HTML data to the browser to interpret the displayed data. But what if you don't want to send the script result back to the browser as a data stream, but instead want to send a page that exists? What if you just want the script to do something without letting any result answer to the browser?

Don't be afraid, let's start explaining these situations here.

Response to call another text

CGI output does not require a data stream. Sometimes you can tell the browser that there is a page on the server. In order to send this information, see the following example:
Location: ../docs/
This Location line is used as the usual output position, that is, if you use Location, you no longer have to use data output like Content-type (in fact, you can't). Just like Content-type, you must also follow this line with a blank line.

The path to this file can be a URL or a relative path. All relative paths refer to the location where the script is located. The text in the example is in the docs directory in the current previous directory:

echo Location: ../docs/


echo

You cannot use both Content-type and Location outputs at the same time. For example, if you want to output a standard page but want to add the client's content at the end of this page, you have to use Content-type to form these two parts by yourself. Note: You can use script commands to open a local file as data and output it directly.

No Response

Sometimes there may be no output for a CGI script. Sometimes you just want to collect some information from the user. You don’t have to call a new text, or output the result or open an existing file. The screen on the browser is still the same.

Fortunately, it's all easy. You just need to output the following command (after a blank line):

echo Status: 204 No Response


echo
This Status header provides the status code to the server (and also to the browser). The special 204 will be passed to the browser and if it can be recognized, it will do nothing.


 


Although unresponsiveness is part of an official HTTP regulation, it is not suitable for all browsers and may produce strange results. You should try it more.

Scripts for processing forms

Today, most CGI scripts are used to process form input. This process is roughly the same as mentioned above, but it is still a little different, such as if the CGI script is called; how data is sent from the server to the browser.

Remember, most forms have two parts: HTML form format; CGI scripts that process form data. This CGI script is called using the tag <FORM> attribute.

Form Form and Form Script

As mentioned above, since the form has two parts. Here is:

This ACTION property contains scripts for processing the form:

<FORM ACTION="/cgi-bin/processorscript">
In this form, each input area has a NAME attribute to call the form element. When the form data is submitted to the CGI script you defined in ACTION, the name and input content are passed to the script as a number or character.

GET and POST

There are two ways to send forms from the browser to the server. GET and POST.

The method we talked about above is actually GET, which places the data package in the environment variable QUERY_STRING as part of the URL as a whole to pass to the server.

POST does a lot of the same things as GET, the difference is that it passes data separately to the script. Your script gets this data through standard input. (Some web servers are stored in temporary files.) This QUERY_STRING environment variable will no longer be set.

So which method do you use? POST is a safe method, especially if your form has a lot of data. When you use GET, the server allocates the variable QUERY_STRING to all form data, but the amount of storage that variable can be limited. In other words, if you have a lot of data but you use GET, you will lose a lot of data.

If you use POST, you can use as much data as possible because the data is never allocated to a variable.

URL encoding

URL encoding is a format used by browsers to package form input. The browser gets all names and values ​​from the form, encodes them as name/value parameters, removes characters that cannot be transferred, ranks data, etc. These depend on whether you use GET or POST? as part of the URL or separately sent to the server. In either case, the form input format on the server side looks like this:
theName=Ichabod+Crane&gender=male&status=missing&headless=yes
URL encoding follows the following rules:
  • Each pair of name/value is separated by the & character.
  • Each pair of name/values ​​from the form is separated by the = character. If the user does not enter a value to this name, then the name still appears, but has no value (like "name=").
  • Any special characters (that are not simple seven-digit ASCIIs, such as Chinese characters) will be encoded in hexadecimal with percentage %. Of course, special characters such as =, &, and % are also included.
  • The spaces in the input area will be displayed with a plus sign +.
Because form input is passed to your script using this URL encoding, you must decode it before you use these parameters, because decoding is a very common job and there are many tools to do this work. You don't need to write this decoding program yourself.

Here is a decoding program called uncgi, you can/~koreth/. Get the original code and install it in your own cgi-bin directory.

Exercise 3: Tell me your name.
Let's use this example to illustrate, as shown in Figure 5.

Figure 5. A form that tells me your name.

This input is sent to the script and then sent back the message showing a hello (Figure 6).

What happens if you don't type anything in your name input? See Figure 7.

Figure 6. Results of the name form.

Figure 7. Another result.

Modify the HTML of the form
Now let's give a real example:
<FORM METHOD=POST ACTION="../cgi-bin/form-name">


</FORM>
If you are using uncgi to decode from input, the situation is a bit different. In order for uncgi to work properly, you must first call uncgi , if uncgi is a directory, plus the actual script name, like this:
<FORM METHOD=POST ACTION="../cgi-bin/uncgi/form-name">


</FORM>
This way, you don't have to modify the original HTML in the form; the original HTML works just fine.
script
The CGI script that processes the input of the form, let's take a closer look.

The first step in the script is decoding. In this example, we have used uncgi to decode the input data. In fact, this form has been decoded for you. By creating an uncgi directory, once the form is submitted to the server, the server will automatically decode it, so that all the name/values ​​are ready to wait for your use.

Now, the beginning part of an example assumes the following:

echo Content-type: text/html


echo


echo "<HTML><HEAD>"


echo "<TITLE>Hello</TITLE>"


echo "</HEAD><BODY>"


echo "<P>"
Next, there are two situations to deal with: one is to deal with the situation where the user does not enter a name, and the other is to say hello to them if it is entered.

The value of this Name element is included in the WWW_theName environment variable. With a simple test command (-z), you can check whether the environment variable is empty or includes the corresponding output value:

if [ ! -z "$WWW_theName" ]; then


    echo "Hello, "


    echo $WWW_theName


else


    echo "You don't have a name?"


fi
Finally, add a connection "go back" to return:
echo "</P><P><A HREF="../lemay/">Go Back</A></P>"


echo "</BODY></HTML>"
 

question

Here is a common problem with using CGI scripts:
  • The script content is only displayed but not executed.

    Have you configured your server to run CGI scripts correctly? Are your scripts placed in the cgi-bin directory? If your server allows CGI with .cgi extension to run, is this the extension for your script filename?

  • Error 500: Server doesn't support POST.

    The answer is still the same as the previous one, and then you execute your CGI using the command line. Can it run normally? Is there any error? .

  • Document contains no data.

    Make sure there is a blank line between your header line and the data section.

  • Error 500: Bad Script Request.

    Make sure your script is executable (on UNIX, use chmod +x your script.cgi). Before running from the browser, you should run your script from the command line. If the client is win95, you can log in to your server with telnet and execute the command line. Of course, you must understand UNIX commands.

CGI variables

Table 2 summarizes those environment variables.
    Table 2. CGI environment variables.
 
Environment variables
significance
SERVER_NAME The host name and IP address of the CGI script when it is running.
SERVER_SOFTWARE The type of your server is: CERN/3.0 or NCSA/1.3.
GATEWAY_INTERFACE The CGI version running. For UNIX servers, this is CGI/1.1.
SERVER_PROTOCOL The HTTP protocol run by the server. Here it is HTTP/1.0.
SERVER_PORT The TCP port that the server runs, usually the web server is 80.
REQUEST_METHOD POST or GET, depending on how your form is submitted.
HTTP_ACCEPT  Content-types that the browser can directly receive can have an HTTP Accept header definition.
HTTP_USER_AGENT The name, version and other platform additional information of the browser that submitted the form.
HTTP_REFERER The URL of the text that submits the form, not all browsers send this message, don't rely on it
PATH_INFO Additional path information is sent by the browser through the GET method.
PATH_TRANSLATED The path information specified by the system in PATH_INFO.
SCRIPT_NAME The path to this CGI script is displayed in the URL (for example, /cgi-bin/thescript).
QUERY_STRING Script parameters or form input items (if submitted by GET). QUERY_STRING contains the parameters after the question mark in the URL.
REMOTE_HOST The host name of the submitted script, this value cannot be set.
REMOTE_ADDR The host IP address of the script.
REMOTE_USER Submit the username of the script. This value can be set if the authentication of the server is activated.
REMOTE_IDENT If the web server is running on ident (a protocol that confirms that the user is connected to you), and the system that submits the form is also running ident, this variable contains the ident return value.
CONTENT_TYPE If the form is submitted with POST, this value will be application/x-www-form-urlencoded. In the form that uploads the file, content-type is a multipart/form-data.
CONTENT_LENGTH For forms submitted with POST, the number of bytes in the standard input port.

Decoding program for form input

There are currently two programs: uncgi for general purpose, and, which is a Perl library for CGI scripts written in perl.

Of course, there are also programs that can be decoded when the form is uploaded, and very few.

uncgi

The original code can be found from/~koreth/get.

This is written by Steve Brenner, helps you manage input. He can get input from GET and POST and place it in a Perl list or array. The updated version can also handle file uploads from the form. From here you can get information and original code/cgi-lib. If you decide to process your form input in Perl language, cgi-lib is a good library.

For use, you usually write this:
#!/usr/lib/perl

require '';
Although there are many subroutines in cgi-lib, the most important thing is the ReadParse subroutine. ReadParse read input conveniently stores name/value in a Perl array. This is usually called in your Perl script:
&ReadParse(*in);
In this example, the array name is in, which can be named at will.

After decoding the form, you can read and process the name/value by following the following:

print $in{'theName'};
This will display the value of the name name which is theName.

If you have multiple name pairs with the same name, separate multiple names with (\0). This will handle your script normally.

Decode uploaded file input

Form-based file uploads require different form inputs, and there are programs that can decode them.

Later versions can be very supportive,/cgi-lib/Learn more.

Another CGI address that handles Perl is/cgi_docs.html .

Do it yourself

Find special books to study:ftp:///rfc/.

Non-anatomical script head

As explained in this book, most cases can operate normally, but in some cases this is not the case. You can read the instructions to learn about it.

<ISINDEX> script

In order to complete the discussion group in CGI, let's take a look at the search called <ISINDEX>. This is an early method used in the browser to issue search keywords to the server, see previous information.

Summarize

CGI scripts, sometimes called server-side scripts or gateway scripts. There are many free resources on the Internet, you can search and download and understand them, of course they are all in English. If you make up your mind to translate them (maybe more understanding). This kills two birds with one stone.

Note: The above program can be edited with ultra edit. Note that the UNIX format must be saved in UNIX format, uploaded, log in with telnet, type perl on the command line to see if there are any bugs, and then call it in the browser. The CGI program must change the attribute to 777 when placing the CGI directory, and the HTML file to be written must also change the attribute to 777.

There are many free cgis on the Internet now, which can basically meet general needs. Please go to this website to check the cgi you want:/cgicollection/

I have Chineseized an ancient general guest book, which everyone can use to make their own guest book.Download here