A good piece of CGI script Learning)

Source: Internet
Author: User
Tags perl script

Learn CGI scripts(SCRIPT) CGI indicates the Common Gateway Interface, a Program Method Based on browser input and running on the Web server. CGI scripts allow your browser to interact with users. In order to find a term in the database and provide comments you write, you can also select several entries from a form and get a clear answer. if you have ever entered a form or searched on the web, you are using a CGI script. you may not realize it at that time, because most of the work is run on the server, and all you see is the result.

As a web designer, you create a CGI script on the client. programs on the server side are used to process user input and the results are returned to the user.

Here you will learn everything about CGI scripts:

  • What is a CGI script? How does it work?
  • What is the output of a CGI script?
  • How to Create a CGI script with or without Parameters
  • How to Create a CGI script that returns a Specified Response
  • How to Create a CGI script for an input form
  • Questions about Using CGI scripts
  • CGI variables that you can use in the script
This section assumes that it is in a UNIX system.

What is a CGI script?

A cgi script is a program running on a Web server. It is triggered by browser input. This script is usually like a bridge between a server and other programs in the system, such as a database.

Isn't the CGI script a real script? According to the support of your server, they may be a compiled program, a batch of command files, or other executable things. For the sake of simplicity, we collectively refer to them as script scripts.

A cgi script is a program running on a web server. CGI indicates a Common Gateway Interface.

CGI scripts use the following two methods: ACTION as a form or direct link in a page.

How does the CGI script work?

CGI scripts have server calls and browser-based data input. Figure 1 shows the process between the browser, server, and script.

Figure 1. Remember to come back from the browser to the server to the script to the program!

Here is a brief illustration:

  1. A URL points to a CGI script. the URL of a CGI script can appear anywhere like a normal URL.
  2. The server receives the request and executes the script according to the script file pointed to by the URL (pay attention to the file location and extension.
  3. The script performs operations based on input data, including querying the database, calculating the value, or calling other programs in the system.
  4. Scripts generate output results that can be understood by a Web server.
  5. The server receives the output from the script and sends it back to the browser to let the user know the result.

A simple example

Here we will explain in detail all the relevant details step by step.
There is an example in Figure 2:
Figure 2. page with a script connection.

Display Date is a connection pointing to the CGI script. Its HTML is like this:

<A HREF="http://www.popchina.com/cgi-bin/getdate">Display the Date</A>

It indicates a CGI script because there is a cgi-bin path. In many servers, cgi-bin is a directory where only CGI scripts can be placed.

When you select this connection, your browser will send a request to the www.popchina.com server. The server will receive this request to calculate the script file name at the URL and then execute this script.

The getdate script is executed in UNIX as follows:

#!/bin/shecho Content-type: text/plainecho/bin/date

The first line is a special command that tells the UNIX system that this is a shell script. The actual situation is the next line starting from this line. This script does two things: it outputs the line Content-type: text/plain, and then starts an empty line. Second, it calls the UNIX system time date program to output the date and time. the output after the script is executed should be as follows:

Content-type: text/plainTue Oct 25 16:15:57 EDT 1994

What is this Content-type? It is a special encoding. The Web server is used to tell the browser what type the text is output. This is the same as the Content-type in HTML.

In this way, the browser outputs 3.

Figure 3 date Script output result.

This is the most basic, and the actual situation is much more complicated. In short, it can be used to understand how the browser, server, and script work.

Can I use CGI scripts?

Before using CGI scripts, you may have two things to solve: CGI scripts are advanced Web features and require the same knowledge as Web Server managers.

Are you sure you want? I just can't do it. Can I study? Okay! Let's continue.

Does your server configuration allow CGI scripts?

To write and run CGI scripts, you need a Web server. unlike Common HTML files, you cannot write or test your CGI script on a local system. You have to do this on a Web server.

However, even if you have a Web server, this server must be specially configured to run the CGI script, which means that all your scripts must be placed in a directory named cgi-bin.

Before writing a CGI script, ask your server manager if you want to allow you to install and run the CGI script. If you can, where do they have to be placed? Also, you must have a real Web server. If it is an FTP or Gopher server, you cannot use CGI.

If you are running on your server, you must create a directory named cgi-bin and configure your server to recognize this directory as a script directory. you must also remember the following CGI script features:

  • Each script is a program that runs on the system that the browser can request and uses the CPU time and memory for execution. What if there are thousands of these scripts running at the same time? Your system will not bear the load until it crashes.
  • If you do not write your CGI script carefully, you may let others access your system through your CGI script parameters.

Will you program?

Attention for beginners! Generally, you must have some basic programming concepts and methods. You must have experience working on similar systems. If you do not have these backgrounds, you must study. Well, you have to spend more time.

What programming language do you need to use?

You can write CGI scripts in any language you are familiar with, as long as your scripts follow the rules displayed in the next section, as long as that language can run on your Web server system.

In this learning 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 handle complicated situations. perl is about to use this language. It is free. It is stable and powerful, similar to C, but it is hard to learn.

Is your server correctly set?

To run any CGI script, whether simple or complex, your server must be set to be able to run them, and must be placed in a specific directory, there must be a file extension that depends on your server.

If you are renting a server, whether to allow the CGI script to run.

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

If you are not using UNIX?

I had to find another learning manual.

Anatomy of a CGI script

If you write it for a long time and overcome many warnings and configurations, congratulations! You have some CGI scripts and can use them on your web page. in this chapter, we will learn how scripts are executed and how your server responds to them.

Output Header

Although your CGI script allows you to do anything, the Script output must still have a prescribed form.
This "Script output" means that your script sends data back to the server. in UNIX systems, the output is a standard output from where the server detects it. in other systems and servers, Your Script output may be different.

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

There are three types of headers: Content-type, Location, and Status. Content-type.

For content-type explanations, see the description of HTML. A specific encoding you can issue is as follows:

Content-type: text/html

In this example, the output data type is text/html. In other words, it is an HTML file.

    Table 1. Common formats and content-types.
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 an empty line. If there is no blank line, the server will not be able to figure out where the header ends.

Output Data

The data you output should comply with your specified content-type. 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 for outputting dates. The CGI script also checks whether I have logged on to my Web server and reports what I found (as shown in Figure 4 ).

Figure 4. Script result
This is a simple example. It can be called as follows:

<A HREF="http://www.popchina.com/cgi-bin/pinglaura">Is Laura Logged in?</A>

This is a script without input. It only runs and returns data.

As described above, the script content is as follows ::
#! /Bin/sh

Echo Content-type: text/html

Echo "<HTML> <HEAD>"

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

Echo "</HEAD> <BODY>"
To test whether I have logged on to the system, run the "who" command (my login name is assumed to be "lemay") and store the result in the variable "ison. if I log on to the system, the variables ison will have some content, otherwise it will be empty.

ison='who | grep lemay'

The test results and the script that returns the corresponding prompt are as follows:

if [ ! -z "$ison" ]; then        echo "<P>Laura is logged in."</P>else        echo "<P>Laura isn't logged in."</P>fi

Close HTML:

echo "</BODY></HTML>"

Now you run him from the command line and test it. You will get a result saying that I have not logged on to your system. Of course it is impossible. His output is as follows:

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 Manager, you can't create a CGI-bin directory by yourself. It's useless.

The complete script for this example is as follows:

#!/bin/shecho "Content-type: text/html"echoecho "<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"fiecho "</BODY></HTML>"

Script with Parameters

To pass a parameter to the script, you can use (?) in the URL (?) Insert a script between nouns and parameters, and use the plus sign (+) to represent each single parameter, for example:
<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 stage.

Exercise 2: Check whether someone has logged in.

Now that you know how to use parameters, let's continue with the above example pinglaura. By modifying this example, we will get the following script pinggeneric.

Let's take a different question:

#!/bin/shecho "Content-type: text/html"echoecho "<HTML><HEAD>"echo "<TITLE>Are You There?</TITLE>"echo "</HEAD><BODY>"

In the above example, the next step is to test whether or not I log on. Here we use the parameter $ {1} instead of my name lemay, and $ {1} as the first parameter, $ {2} is the second and $ {3} is 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>"

Now, let's modify the link on the HTML page! It turns out to be like this:

<A HREF="http://www.lne.com/cgi-bin/pinglaura">Is Laura Logged in?</A>

The general query function is modified as follows, for example, to query whether a person named john logs in:

<A HREF="http://www.lne.com/cgi-bin/pinggeneric?john">Is John Logged in?</A>

Try it on your server to see if there is any result.

Pass other information to the script

There is a second way to pass the information to the CGI script. it is called path information. path information is used as a parameter that does not need to be changed during script calling, like a temporary file name or a file name that calls the script itself. as you can see, the parameters after the question mark in the above example are changed due to the input of the user form. path info is used to pass other information to the script. In fact, you can use it to do anything.
Path information is not as frequently transmitted as common parameter scripts. path information usually refers to files on the Web server, such as configuration files, temporary files, or files called by scripts due to problems.

See the following path information example ,:


When the script runs, 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 to display the connected HTML file name. in this way, after processing your script, when you send back an HTML file, you can include a connection in the file and send back the page from the beginning of the user.

You will learn more about paths in the next chapter: Useful Forms and scripts.

Create a special Script output

Now you have learned how to send HTML data, for example, output data, to the browser to explain the displayed data. but if you don't want to send the script result back to the browser as a data stream, but want to send back an existing page, what should you do? What if you only want scripts to do something and don't let any results be answered to the browser?

Don't worry. Here we will explain these situations.

Call another text as a response

CGI output does not have to be a data stream. Sometimes it can tell the browser that there is a page on the server. To send this information, see the following example:
Location: ../docs/final.html

This Location row is used as the usual output Location. That is to say, if you use Location, you do not need to use data output such as Content-type (in fact, you cannot ). just like Content-type, you must follow this line with an empty line.

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

echo Location: ../docs/final.htmlecho
You cannot use both Content-type and Location outputs. for example, if you want to output a standard page, but want to add the customer's Content at the end of the page, you have to use Content-type to create these two parts. note: You can use a script command to open a local file and output it directly as data.

No Response

Sometimes there may be no output for a CGI script. sometimes you just need to collect some information from the user. you do not need to call a new text or output results or open an existing file. the screen on the browser still looks like that.

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

echo Status: 204 No Responseecho

This Status header provides the Status code to the server (and also to the browser). A special 204 will be passed to the browser. If it can recognize it, it will do nothing.

Although no response is part of an official HTTP rule, it is not suitable for all browsers and may produce strange results. Try it more.

Form processing script

Today, most CGI scripts are used to process form input. this process is roughly the same as described above, but it is still somewhat different. For example, as long as 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 script for processing FORM data. This CGI script is called using the tag <FORM> attribute.

Form and form script

As mentioned above, the form has two parts:

This ACTION property contains the script for processing the form:

<FORM ACTION="http://www.popchina.com/cgi-bin/processorscript">

In this form, each input area has a NAME attribute, which is used to call form elements. when the form data is submitted to the CGI script defined in the ACTION, the name and input content are passed to the script as a number or character.


There are two ways to send a form from the browser to the server: GET and POST.

The method we discussed above is actually GET, which packs the data and places it in the environment variable QUERY_STRING as a part of the whole URL and passes it to the server.

POST does many similar GET operations. The difference is that it transmits data to the script separately. your script obtains the data through standard input. (Some Web servers are stored in temporary files .) the QUERY_STRING environment variable will not be set.

What method do you use? POST is a safe method, especially if your form contains a lot of data. when you use GET, the server assigns the variable QUERY_STRING to all form data, but the variable has limited storage capacity. 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 a browser to package form input. the browser obtains all names and values from the form, encodes them as the name/value parameter, removes characters that cannot be transferred, and ranks the data, depends on whether you use GET or POST? As part of the URL or sent to the server separately. In either case, the form input format on the server is as follows:

URL encoding follows the following rules:

  • Each pair of name/value is separated by the & operator.
  • Each pair of name/value from the form is separated by a = character. If the user does not enter a value for this name, this name still appears, but there is no value (such as "name = ").
  • Any special characters (that is, those that are not simple seven-digit ASCII, such as Chinese characters) will be encoded in hexadecimal notation with percentages. of course, it also contains special characters such as =, &, and %.
  • Spaces in the input area are displayed with the plus sign +.

Because form input uses this URL encoding to pass to your script, it must be decoded before you use these parameters, because decoding is a common task, there are many tools to do this. you do not have to write this decoder yourself.

Here we introduce a decoding program called uncgi that you can get from http://www.hyperion.com /~ Koreth/uncgi.html. Obtain 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: 5.

Figure 5. The form that tells me your name.

The input is sent to the script, and a hello message is returned (figure 6 ).

What if you do not enter anything in the Name field? See Figure 7.

Figure 6. Name form result.

Figure 7. Another result.

Modify the HTML of a form

Here is a real example:
<FORM METHOD=POST ACTION="../cgi-bin/form-name"></FORM>

If you are decoding from input using uncgi, the situation is a bit different. to ensure that uncgi works properly, you must first call uncgi. If uncgi is a directory, add the actual Script Name, as shown in the following figure:

<FORM METHOD=POST ACTION="../cgi-bin/uncgi/form-name"></FORM>

In this way, you do not have to modify the original HTML in the form; the original HTML can work well.


The input in the form is a CGI script. 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. The actual form has been decoded for you. by creating an uncgi directory, once the form is submitted to the server, the server will automatically perform decoding, so that all names/values are ready for your use.

Now, the first part of an example is assumed as follows:

echo Content-type: text/htmlechoecho "<HTML><HEAD>"echo "<TITLE>Hello</TITLE>"echo "</HEAD><BODY>"echo "<P>"

Next, there are two situations to deal with: one is to handle the situation where the user does not enter a name, and the other is to say hello to the user if the user inputs.

The value of this Name element is contained 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 values:

if [ ! -z "$WWW_theName" ]; then    echo "Hello, "    echo $WWW_theNameelse    echo "You don't have a name?"fi

Add a connection "go back:

echo "</P><P><A HREF="../lemay/name1.html">Go Back</A></P>"echo "</BODY></HTML>"


Here is a common problem with CGI scripts:

  • The script content is only displayed and not executed.

    Have you correctly configured your server to run the CGI script? Is your script in the cgi-bin directory? If your server allows cgi running with the. CGI extension, is the extension of your script file name like this?

  • Error 500: Server doesn' t support POST.

    The answer is the same as the previous one. Can you run your CGI through the command line? Are there any errors ?.

  • Document contains no data.

    Make sure there is a blank line between your header row and data department.

  • Error 500: Bad Script Request.

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

CGI variable

Table 2 summarizes the environment variables.

    Table 2. CGI environment variables.
Environment Variable
SERVER_NAME The Host Name and IP address when the CGI script is running.
SERVER_SOFTWARE The type of your server, such as CERN/3.0 or NCSA/1.3.
GATEWAY_INTERFACE The running CGI version. For UNIX servers, this is CGI/1.1.
SERVER_PROTOCOL The HTTP protocol running on the server. The HTTP/1.0 protocol is used here.
SERVER_PORT The TCP port running on the server. Generally, the Web server is 80.
REQUEST_METHOD POST or GET depends on how your form is submitted.
HTTP_ACCEPT Content-types that can be directly received by the browser, which can be defined by the HTTP Accept header.
HTTP_USER_AGENT The name, version, and additional platform information of the browser that submits the form.
HTTP_REFERER The URL of the text to submit the form. Not all browsers send this message and do not rely on it.
PATH_INFO The additional path information is sent by the browser through the GET method.
PATH_TRANSLATED The path 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 with GET). QUERY_STRING contains parameters following the question mark in the URL.
REMOTE_HOST Host Name of the submitted script. This value cannot be set.
REMOTE_ADDR Host IP address of the script submitted.
REMOTE_USER User name for script submission. This value can be set if Server authentication is activated.
REMOTE_IDENT If the Web server is running on ident (a protocol that confirms that the user is connected to you), the system that submits the form is also running ident, and this variable contains the ident return value.
CONTENT_TYPE If the form is submitted using POST, the value will be application/x-www-form-urlencoded. In the form for uploading files, content-type is a multipart/form-data.
CONTENT_LENGTH The number of bytes in the standard input port for the form submitted using POST.

Form input decoding program

There are currently two programs: General purpose uncgi, and cgi-lib.pl, which is a Perl library for CGI scripts written in perl.

Of course, there are also few programs that can be decoded during form upload.


The original code can be from http://www.hyperion.com /~ Obtained from koreth/uncgi.html.


This is written by Steve brner to help you manage input. it can GET input from GET and POST and put it in a Perl list or array. the updated version can also process file uploads from the form. here we can get information with the original code http://www.bio.cam.ac.uk/cgi-lib. if you decide to use Perl to process your form input, cgi-lib is a good library.

To use the cgi-lib.pl, you usually need to write like this:
#! /Usr/lib/perl

require 'cgi-lib.pl';

Although there are many subprograms in cgi-lib, the most important thing is the ReadParse subprogram. readParse reads the input and stores the name/value in a Perl array. in your Perl script, it is usually called as follows:


In this example, the array name is in.

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

print $in{'theName'};

This will display the value whose name is theName.

If you have multiple name pairs with the same name, the cgi-lib.pl uses (\ 0) to separate multiple names. This will process your script.

Decode the input of the uploaded file

Form-based file upload requires different form inputs, and some programs can decode them.

Cgi-lib.pl later versions can be well supported, learn more in http://www.bio.cam.ac.uk/cgi-lib.

Another CGI address written in Perl is a http://valine.ncsa.uiuc.edu/cgi_docs.html.

Do it yourself

Find special books to learn it: ftp://ds.internic.net/rfc/rfc1867.txt.

Non-anatomical script Header

According to this book, most cases can be operated normally. In some cases, this is not the case. You can read the instructions to learn about it.

<ISINDEX> script

To complete the discussion group in CGI, let's look at the search called <ISINDEX>. This is a method that was used to send a search keyword to the server in the browser in the early days. refer to the previous documents.


CGI scripts are sometimes called server scripts or gateway scripts. There are a lot of free resources on the internet. You can search, download, and read them. Of course, they are all in English. If you make up your mind to translate them (maybe more understandable.

Note: The above program can be edited using ultra edit. Note that to convert the UNIX format, you must save the disk in the UNIX format, upload the file, log in via telnet, and type the perl sample in the command line. pl to check whether there are any bugs and then call it in the browser. The CGI program includes the directory where CGI is placed. The attribute must be changed to 777, And the HTML file to be written must also be changed to 777.

Now there are a lot of free cgi online, basically can meet the general needs, please go to this URL to query your cgi: http://www.itm.com/cgicollection/

I have compiled an old general message book. You can use it as your own message book. Download here

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.