CGI Scripting Introductory Learning materials _ Other

Source: Internet
Author: User
Tags emit ftp getdate html form perl script
    • What is a CGI script?
      • How does a CGI script work?
      • A simple example
    • Can I use a CGI script?
      • Does your server configuration allow CGI scripts?
      • Can you program it?
      • What programming language should you use?
      • Is your server set up correctly?
      • What if your server is not a UNIX system?
    • Anatomy CGI Script
      • Output Head
      • Output Data Department
      • Script with Elaboration
      • Passing other information to the script
    • Create a special script output
      • To load another text response
      • No response
    • Script that processes a form
      • form formatting and form scripting
      • Get and POST
      • URL encoding
    • Problem
    • CGI variables
    • Decoding program
      • uncgi
      • cgi-lib.pl
      • Decoding file Upload input
      • Do It Yourself
    • Non-anatomical head script
    • Summarize


    Learn CGI scripts Script

    CGI meaning is Common Gateway Interface, a browser-based input, a program method that runs on a Web server. CGI scripts enable your browser to interact with the user, to find a noun in a database, to provide comments you write, or to select several entries from a form and get a clear answer. If you've ever met a form or search on the Web, you're using a CGI script. You may not be aware of it, because most of the work is done on the server, and all you see is the result.

    As a web designer, you create a client-side CGI script that is used by the server to process user input, and results are returned to the user.

    Here you will learn everything about CGI scripts:

      • What is a CGI script? How does it work?
      • What does a CGI script output like?
      • How to create a CGI script with parameters or no parameters
      • How to create a CGI script that returns a specified response
      • How to create a CGI script that enters a form
      • Questions about using CGI scripts
      • The CGI variables you can use in the script
    This section is assumed to be under UNIX systems.

    What is a CGI script?

    The CGI script is simply a program running on a Web server, with input from the browser triggering. This script is often used as a bridge between servers and other programs in the system, such as databases.

    Isn't a CGI script a real script? With the support of your server, they may be a compiled program or batch command file or something else that can be executed. For simplicity's sake, we collectively refer to them as scripting scripts.

    A CGI script is any program that runs on a Web server. CGI means common Gateway Interface.

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

    How does a CGI script work?

    CGI scripts have server calls, browser-based data entry. Figure 1 shows what a process is between a browser, a server, and a script.

    Figure 1: From browser to server to script to program remember to come back.

    Here's a short schematic explanation:

      1. A URL points to a CGI script. The URL of a CGI script can appear anywhere in the same way as a normal URL.
      2. The server receives the request and executes the script according to the script file that the URL points to (note the location and extension of the file).
      3. Scripts perform operations based on input data, including querying the database, calculating values, or invoking other programs in the system.
      4. The script produces output that some 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 is a step-by-step explanation of all the details of the occurrence.
    In Figure 2, there are a few example figures:
    Figure 2. A page with a script connection.

    Display date is a connection that points to a CGI script. Its HTML is like this:

    <a href= "Http://www.popchina.com/cgi-bin/getdate" >display the date</a>
    The description is a CGI script because there is a cgi-bin path in it. In many servers Cgi-bin is the only directory where CGI scripts can be placed.

    When you select this connection, your browser will make a request to the www.popchina.com server. The server receives the request to compute the script filename at the URL and executes the script.

    This getdate script, executed on UNIX systems, is 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 thing is that the next line from this line, the script does two things: it outputs the row content-type:text/plain, then starts a blank line; second, it invokes the UNIX system time date program, which outputs the date and time. The output should be this way after the script executes:
    Content-type:text/plain 
    
    
    Tue Oct 16:15:57 EDT 1994
    What is this content-type? It's a special code that the Web server uses to tell the browser what type of text to print. This is the same as the Content-type meaning in HTML.

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

    Figure 3 Date script output results.

    This is the basics, the reality is much more complex, and can be used to understand how browsers, servers, and scripts work.

    Can I use a CGI script?

    Before you use a CGI script, there are two things you might want to solve: a CGI script is an advanced Web feature and requires as good a knowledge as a Web server administrator.

    Are you sure? Just can't do it, can you learn it? All right! Let's move on.

    Does your server configuration allow CGI scripts?

    To be able to write and run CGI scripts, you need a Web server. Unlike the usual HTML files, you can't write or experiment with your CGI scripts on the local system; You have to do this through a Web server.

    But even if you have a Web server, the server must be specifically configured to run a CGI script. That means that all of your scripts must be placed in a directory called Cgi-bin.

    Before you write a CGI script, ask your server administrator if you want to allow you to install and run the CGI scripts, and if so, where should they be placed? Also, you have to have a real Web server, if it's an FTP or gopher server, you can't use CGI.

    If you are running on your own server, you must specifically create a directory called Cgi-bin and configure your server to endorse this directory as a script directory. You must also remember the following features about CGI scripting:

      • Each script is a program that runs on a system that the browser can request, using CPU time and memory for execution. What if there are thousands of scripts running at the same time? Your system will not bear to load until it crashes.
      • If you don't write your CGI script carefully, you'll be able to get someone else to hurt your system through your CGI script parameters.

    Do you know how to program?

    Beginner's attention! Generally, you must have some basic programming concepts and methods. You must have experience working with similar systems. If you don't have these backgrounds, you have to learn, well, crap don't say much.

    What programming language do you have to use?

    You can write CGI scripts in any language that you are familiar with, as long as your scripts follow the rules shown 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: the UNIX shell and the Perl language. 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, this language, it is free, the language is stable and powerful, similar to C, but it is also more difficult to learn.

    Is your server set up correctly?

    In order to run any CGI scripts, 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 relies on your server settings.

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

    If you have your own server, check your server instructions on how to handle the CGI script.

    And if you're not using UNIX?

    I had to find another learning manual.

    Dissect a CGI script

    If you write it for a long time, overcome a lot of warnings and configurations, congratulations, you already have some CGI scripts that you can use on your Web page. In this chapter, you will learn how scripts are executed, and how your server responds to their conversations.

    Output Head

    Although your CGI script will allow you to do anything, the output of the script must have a prescribed form.
    This "script output" means the data that your script sends back to the server. In a UNIX system, the output is sent to the standard output, and the server detects it from there. In other systems and servers, your script output may not be the same.

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

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

    For Content-type explanations you can see a description of HTML, a specific encoding you can emit like this:

    Content-type:text/html
    In this example, the type of output data is text/html; In other words, he is an HTML file.
        table 1. General format 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 the Content-type must follow a blank line. If you don't have a blank line, the server will not be able to figure out where the head ends.

    Output data

    The data you output should conform to the content-type you have stipulated; If the Content-type is text/html, the output placement should be in HTML. If Content-type is image/gif, the output should be in a binary GIF file.

    Exercise 1: Try a little.

    T this is a simple script for the output date, and this CGI script also checks to see if I have logged on to my web server and what the report found (as in Figure 4).

    Figure 4. Results of the script
    This is a very simple example of how he can make a call:

    <a href= "Http://www.popchina.com/cgi-bin/pinglaura" >is Laura logged in?</a>
    This is a script that is not entered, it only runs and returns data.

    According to the previous elaboration, this script content is this::
    #!/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, use the WHO command (my login name assumes LeMay) to store the results in the variable ISON. If I log in, the variable ISON will have some content, otherwise it is empty.

    Ison= ' who | grep LeMay '
    The test results and the script that returns the corresponding prompts are:
    if [!-Z "$ison"]; Then 
    
    
    echo "<p>laura is logged in." </P> 
    
    
    Else 
    
    
    echo "<p>laura isn ' t logged in." </P> 
    
    
    fi
    Finally turn off HTML:
    echo "</BODY></HTML>"
    Now you run him from the command line, test it, you'll get a result that says I didn't log on to your system, of course not, and his output is this:
    content-type:text/html 
    
    
    <HTML><HEAD> 
    
    
    <title>are you there?</title> 
    
    
    
    This is the output of an HTML text so your browser can display him properly because he is an HTML file.


    Now copy him to your server's Cgi-bin directory and execute it, if you can't reach the Cgi-bin directory, you have to ask your Server Manager, you can't take it for granted that you can build a cgi-bin directory yourself, that's 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= 's" who 
    
    | grep lemay ' 
    
    if [!-Z ' $ison]; t Hen 
    
    echo "<p>laura is logged in" 
    
    else 
    
    echo "<p>laura isn ' t logged in" 
    
    fi
          
           echo "</BODY></HTML>"
          

    Script with parameters

    To pass a parameter to the script, you can insert a script noun and parameter in the URL using a plus sign (+) to denote 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 arg1, arg2, and Arg3 parameters to the script. You can then use these parameters in the script.

    This method is sometimes called a query because it is used in the search function earlier.

    Exercise 2: Check to see if anyone is logged in.

    Now that you know how to use parameters, let's continue with the above example Pinglaura, and by modifying this example we get the following script Pinggeneric.

    Let's take a different topic:

    #!/bin/sh 
    
    
    echo "content-type:text/html" 
    
    
    echo 
    
    
    echo <HTML><HEAD> " 
    
    
    echo" <TITLE> Are you there?</title> " 
    
    
    echo" </HEAD><BODY> "
    In the above example, the next step should be to test whether I log in, where we use the parameter ${1} instead of my name LeMay, ${1} as the first parameter, ${2} as the second, ${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 change the connection in the HTML page! It turns out that:
    <a href= "Http://www.lne.com/cgi-bin/pinglaura" >is Laura logged in?</a>
    This is done after modifying the universal query function, such as whether the person named John is logged on:
    <a href= "Http://www.lne.com/cgi-bin/pinggeneric?john" >is John logged in?</a>
    Try it on your server to see if there are any results.

    Passing other information to the script

    There is a second way of passing information to a CGI script. It's called path information. Path information is used as a parameter that is not changed in script invocation, like a temporary filename or call script own filename. As you can see, the arguments at the end of the example above are changed by the input of the user form. Path info is used for other information to pass to the script, and you can actually do anything with it.
    Path information path information is a way of not passing information as frequently as the usual parameter scripts. Path path information typically refers to files such as configuration files, temporary files, or files that are invoked by a script because of a problem on a Web server.

    Look at one of the path information Paths Information example,:

    Http://myhost/cgi-bin/myscript/remaining_path_info?arg1+arg2
    When the script runs, the information in the path is placed in the environment parameter path_info. You can use this information in the content of your scripts.

    For example, let's say that you already have multiple connections to the same script on multiple pages. You can use this path information to display the connected HTML file name. So, after you've finished processing your script, when you send back an HTML file, you can include a connection in the file and send it back to the user at the beginning of the page.

    You'll learn more about path information in the next section: useful forms and scripts. To be later logged out

    Create a special script output

    Now you've learned data such as output data that is typically HTML data sent to the browser to interpret the display. But what if you don't want to send the script results back to the browser as a data stream, but instead want to send back a page that exists? What if you just want the script to do something without getting any results answered to the browser?

    Don't be afraid, this is the beginning of the explanation.

    Use to invoke another text as a response

    CGI output does not have to be a data stream, sometimes can tell the browser is the presence of a page on the server, in order to send this message, look at the following example:
    Location:.. /docs/final.html
    This location line is used as the usual output location, which means that if you use a location, you don't have to use the data output like content-type (in fact, you can't). As Content-type, you also have to follow a blank line behind this line.

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

    echo Location:. /docs/final.html 
    
    
    Echo
    You cannot use Content-type and location two outputs at the same time. 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 build these two parts. Note: You can use a script command to open a local file to output directly from the data.

    No Response

    Sometimes for a CGI script, there's probably no output at all. Sometimes you just have to collect some information from users. You don't have to call a new text, you don't have to output a result, or you open a file that exists. The screen on the browser is still that way.

    Luckily, it's all very easy. You only need to output this command (followed by a blank line):

    echo status:204 No Response 
    
    
    Echo
    This status header provides a status code to the server (and also to the browser). The special 204 will be passed to the browser, and if it can be identified, it will do nothing.


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

    Script that processes a form

    Today, most CGI scripts are used to work with form input. This process is roughly as described above, but there are some differences, such as the CGI script as long as it is invoked and how the data is sent from the server to the browser.

    Remember, most forms have two parts: HTML form format, and CGI scripts that work with form data. This CGI script is invoked using tags <FORM> properties.

    form forms and Form scripts

    As mentioned above, there are two parts to the form. As follows:

    This Action property contains the script that handles the form:

    <form action= "Http://www.popchina.com/cgi-bin/processorscript" >
    In this form, each input area has a name attribute that is used to address the form element. When this form data is submitted to the CGI script you defined in the action, the name and input content is passed as a number or character to the script.

    Get and POST

    There are two ways to send a form to a server from a browser. Get and POST.

    The method we're talking about here is actually get, which packages the data in the environment variable query_string and passes it to the server as part of the URL as a whole.

    Post does a lot of things like get, and the difference is that it sends data to the script in a separate way. 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.

    What do you do with that method? Post is a safe method, especially if you have a lot of data in your form. When you use GET, the server assigns variable query_string to all form data, but the variable can be stored in a limited amount. In other words, if you have a lot of data but you use GET, you lose a lot of data.

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

    URL encoding

    URL encoding is a format that browsers use to package form input. The browser takes all the name and the values from the form, encodes them as name/value parameters, removes the characters that can't be transferred, lists the data, and so on, depending on whether you use Get or post? As part of the URL or as a separate issue 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 these rules:
      • Each pair of Name/value is separated by A & character.
      • Each pair of name/value from the form is separated by the = character. If the user does not enter a value for this name, then the name still appears, but no value (such as "name=").
      • Any special characters (that is, those that are not simple seven-bit ASCII, such as Chinese characters) will be encoded in hexadecimal with a percent character. Of course also include like =,, and% these special characters.
      • Spaces in the input area are displayed with a plus sign +.
    Because the form input is passed to your script with this URL encoding, you must decode it before you use these parameters, because decoding is a common job and there are a lot of tools to do this work. You do not need to write this decoding program yourself.

    Here is a decoding program called UNCGI, which you can get from http://www.hyperion.com/~koreth/uncgi.html. 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.

    Fig. 5. Tell me your name of the form.

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

    What happens if you don't enter anything in the name entry? See Figure 7.

    Figure 6. The results of the name form.

    Fig. 7. Another result.

    Modify the HTML of a 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 little 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 can work very well.

    Script

    Processing the form input 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 decoding input data, the actual form has been done for you to decode. By creating a uncgi directory, once the form is submitted to the server, the server decodes it automatically, so all the Name/value are ready for your use.

    Now, one example begins with the assumption that this is the following:

    echo content-type:text/html 
    
    
    echo echo " 
    
    
    <HTML><HEAD> 
    
    
    echo" <title>hello</title > " 
    
    
    echo" </HEAD><BODY> " 
    
    
    echo" <P>
    Next, there are two things 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 them if entered.

    The value of this name element is contained in the WWW_THENAME environment variable. With a simple test command (-Z), you can see if the environment variable is empty or include 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 to "go back". Used to return:
    echo "</p><p><a href=". /lemay/name1.html ">go back</a></p>" 
    
    
    echo "</BODY></HTML>"

    Problem

    Here's a common problem with CGI scripts:
      • The script content only shows not executing.

        Did you correctly configure your server to run a CGI script? Is your script placed in the Cgi-bin directory? If your server allows CGI to run with a. cgi extension, is this the name extension of your script file?

      • Error 500:server doesn ' t support POST.

        The answer is the same as above, and then you execute your CGI with the command line, can it work? Are there any errors?

      • Document contains no data.

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

      • Error 500:bad Script Request.

        Make sure your script is executable (in Unix, with chmod +x your script. cgi). Before running from the browser, you should run your script from the command line, and if the client is Win95, you can use Telnet to log on to your server, execute the command line, and of course have to 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 at runtime.
    Server_software The type of your server is: cern/3.0 or ncsa/1.3.
    Gateway_interface Run the CGI version. For UNIX servers, this is cgi/1.1.
    Server_protocol The HTTP protocol that the server is running. This is http/1.0.
    Server_port The TCP port that the server is running, usually the Web server is 80.
    Request_method POST or get, depending on how your form is submitted.
    Http_accept The content-types that the browser can receive directly can have the HTTP Accept header definition.
    Http_user_agent Additional information about the name, version, and other platform of the browser submitting the form.
    Http_referer URL that submits the text of the form, not all browsers emit this information, do not rely on it
    Path_info Additional path information that is emitted by the browser through the Get method.
    Path_translated The system-defined path information in the PATH_INFO.
    Script_name The path to the CGI script is displayed in the URL (e.g.,/cgi-bin/thescript).
    Query_string The script parameter or form entry (if it is submitted with get). Query_string contains the arguments that follow the question mark in the URL.
    Remote_host The host name for submitting the script, this value cannot be set.
    Remote_addr The host IP address that submitted the script.
    Remote_user The name of the user who submitted the script. If the server's authentication is activated, this value can be set.
    Remote_ident If the Web server is running in ident (a protocol that confirms the user's connection to you), the system that submits the form is running ident, which contains the ident return value.
    Content_Type If the form is submitted by post, the 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 the form submitted by post, the number of bytes in the standard input port.

    The decoding program for form input

    There are currently two programs: Common Purpose uncgi, and cgi-lib.pl, a Perl library for CGI scripts written in Perl.

    There are, of course, programs that can be decoded when the form is uploaded, rarely.

    uncgi

    Indicates that the original code can be obtained from http://www.hyperion.com/~koreth/uncgi.html.

    cgi-lib.pl

    This is written by Steve Brenner to help you manage your input. He gets input from get and post and places it in a Perl list or array. Newer versions can also process file uploads from forms. From here you 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.

    In order to use cgi-lib.pl, you usually write this:
    #! /usr/lib/perl

    Require ' cgi-lib.pl ';
    Although there are many subroutines in cgi-lib, the most important thing is the Readparse subroutine. Readparse read input makes it easy to store name/value in a Perl array. This is usually called in your Perl script:
    &readparse (*in);
    In this case, the array name is in and can be named casually.

    After the form is encoded, you can read and process the Name/value, as follows:

    Print $in {' thename '};
    This will show the value of name thename.

    If you have multiple name pairs with the same name, Cgi-lib.pl uses () to separate multiple names. This will work correctly with your script.

    Decoding the uploaded file input

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

    Cgi-lib.pl later versions can be very well supported in http://www.bio.cam.ac.uk/cgi-lib/to learn more about the situation.

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

    Do It Yourself

    Find a special book to study: Ftp://ds.internic.net/rfc/rfc1867.txt.

    Non-anatomical script head

    According to this book, most of the situation can be normal operation, in some cases is not the case, you can read the instructions.

    <ISINDEX> scripts

    To complete the discussion group in CGI, let's look at the search called <ISINDEX>. This is the early use of the browser to send a search keyword to the server, refer to previous information.

    Summarize

    CGI scripts, sometimes called server-side scripts or gateway scripts. There are a lot of free resources on the Internet, you can search and download to read them, of course, all in English, if you are determined to translate them (may be more understanding). So kill both birds.

    Note: The above program can be edited with Ultra Edit, note that the UNIX format must be saved in UNIX format, uploaded, Telnet, type perl sample.pl at the command line, see if there are bugs, and then call in the browser. CGI programs include a directory to place the CGI must be changed to 777, the HTML file to be written to be changed to the property of 777.

    Now there are a lot of free CGI online, basic to meet the general needs, please go to this site to inquire about your cgi:http://www.itm.com/cgicollection/

    I have a Chinese ancient general book, you can take to do their own 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.