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
What is a CGI script?
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.
CGI scripts are used in two ways: ACTION as a form or as a direct link in a page.
How do CGI scripts work?
Figure 1. From browser to server to script to programRemember to come back!
Here is a brief explanation:
- A URL points to a CGI script. The URL of a CGI script can appear anywhere like a normal URL.
- 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).
- The script performs operations based on input data, including querying the database, calculating numerical values, or calling other programs in the system.
- The script produces some kind of output that the web server can understand.
- 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
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/dateThe 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 1994What 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?
Sure? You just can't do it, can you learn? All right! Let's continue.
Does your server configuration allow CGI scripts?
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?
What programming language do you have to use?
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?
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?
Dissect a CGI script
Output header
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/htmlIn this example, the output data type is text/html; in other words, it is an HTML file.
Format |
Content-Type |
HTML | text/html |
Text | text/plain |
GIF | image/gif |
JPEG | image/jpeg |
PostScript | application/postscript |
MPEG | video/mpeg |
Output data
Exercise 1: Try it.
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> fiFinally 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.
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
<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.
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
See the following path information example,:
http://myhost/cgi-bin/myscript/remaining_path_info?arg1+arg2When 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
Don't be afraid, let's start explaining these situations here.
Response to call another text
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
No Response
Fortunately, it's all easy. You just need to output the following command (after a blank line):
echo Status: 204 No Response echoThis 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.
Scripts for processing forms
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
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
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
theName=Ichabod+Crane&gender=male&status=missing&headless=yesURL 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 +.
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.
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
<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 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?" fiFinally, add a connection "go back" to return:
echo "</P><P><A HREF="../lemay/">Go Back</A></P>" echo "</BODY></HTML>"
question
- 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
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
Of course, there are also programs that can be decoded when the form is uploaded, and very few.
uncgi
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
Later versions can be very supportive,/cgi-lib/Learn more.
Another CGI address that handles Perl is/cgi_docs.html .
Do it yourself
Non-anatomical script head
<ISINDEX> script
Summarize
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