CGI (Universal Gateway Interface) and cgi universal Gateway Interface

Source: Internet
Author: User

CGI (Universal Gateway Interface) and cgi universal Gateway Interface
Public Gateway Interface

CGI (Common Gateway Interface) is one of the most important technologies in WWW technology and plays an irreplaceable role. CGI is the interface standard between external applications (CGI programs) and Web servers. It is the procedure for transmitting information between CGI programs and Web servers. CGI specifications allow the Web server to execute external programs and send their output to the Web browser. CGI converts a simple set of static hypermedia documents on the Web into a complete new interactive media.

Common Gateway Interface (CGI. Physically, a program runs on the server and provides interfaces on HTML pages of the same client. This is probably hard to understand. Let's look at a practical example: most of my personal pages now have a message book. The work of the message book is as follows: the user first enters some information, such as the name, on the client. Next, the user clicks "Leave a message" (currently working on the client), and the browser sends the information to a specific CGI program in the cgi directory of the server, as a result, cgi programs are processed on the server according to the predefined method. In this example, the information submitted by the user is stored in the specified file. Then the cgi program sends a message to the client, indicating that the request task has been completed. At this time, the user will see the "End of message" in the browser. The whole process is over.

Function

Most CGI programs are used to interpret and process the input information from the form, generate corresponding processing on the server, or feed the corresponding information to the browser. CGI programs enable web pages to interact with each other. Procedure

(1) Send user requests to the web server over the Internet.

(2) The web server receives user requests and submits them to the CGI program for processing.

(3) The CGI program sends the processing result to the web server.

(4) The web server returns the result to the user. Server Configuration

CGI programs can run smoothly without being put on the server. If you want to make them run smoothly on the server and process user requests accurately, you must make necessary settings for the server you are using.

Configuration: the CGI program is placed in a specific directory or with a specific extension according to the server type used and its settings.

(1) configuration of the server in CREN format:

Edit the configuration file (usually/etc/httpd) of the server in CREN format. conf) add Exec cgi-bin/*/home/www/cgi-bin/* to the file /*. exec. The first parameter cgi-bin/* in the command specifies the directory name that appears in the URL and indicates that it appears in the first directory after the system host, such as: http://edgar.stern.nyn. * **/cgi-bin /. The second parameter in the command indicates the actual path of the CGI program directory in the system.

In addition to the network files, the CGI directory can be placed in the same directory or other directories of the system, but you must ensure that the same directory exists in your system. After setting the server, you must restart the server (unless the HTTP server is started with inetd ).

(2) configuration of NCSA Server

There are two ways to set the NCSA format Server:

① Add Script Alias/cgi-bin/to the srm. conf file (usually in the conf directory /. The Script Alias command indicates that the files in a directory are executable programs, and this command is used to execute these programs; the two parameters of this command have the same meaning as the parameters of the Exec command in the CERN format server.

② Add: Add type application/x-httpd-cgi.cgi to the srm. conf file. This command adds a new file type to the server. The first parameter is the MIME type of the CGI program, and the second parameter is the file extension, indicates that the file with this extension is a CGI program.

After setting the server with one of the above methods, You have to restart the server (unless the HTTP server is started with inetd ). Programming Language

CGI can be written in any language as long as it has standard input, output, and environment variables. For beginners, it is best to select a language that is easy to archive and can effectively represent a large amount of data structures, such as in UNIX environments:

· Perl (Practical Extraction and Report Language)

· Bourne Shell or Tcl (Tool Command Language)

· PHP (Hypertext Preprocessor ))

Because the C language has strong platform independence, it is also the first choice for compiling CGI programs.

In Windows:

· C and C ++

Most servers on the Internet use UNIX operating systems, and almost any UNIX operating system has a Bourne Shell. Therefore, most of the examples described later are written using the Bourne Shell.

In the end, because of its cross-operating system and easy-to-modify features, Perl becomes the mainstream programming language of CGI, so that the general "cgi program" is a Perl program.

Environment Variable list

SERVER_NAME: run the CGI Command for the machine name or IP address.

SERVER_INTERFACE: Type of the WWW server, for example, CERN or NCSA.

SERVER_PROTOCOL: communication protocol, which must be HTTP/1.0.

SERVER_PORT: TCP port. Generally, the web port is 80.

HTTP_ACCEPT: the type of data that the HTTP browser can accept.

HTTP_REFERER: the URL of the file that sends the form. (Not all browsers send this variable)

HTTP_USER-AGENT: information about the browser that sends the form.

GETWAY_INTERFACE: the CGI program version. It is CGI/1.1 in UNIX.

PATH_TRANSLATED: the actual path name contained in PATH_INFO.

PATH_INFO: Additional path used by the browser to send data in GET mode.

SCRIPT_NAME: The Path Name of the CGI program.

QUERY_STRING: the data entered in the form, the content after the question mark in the URL.

REMOTE_HOST: the sender's host name, which cannot be determined.

REMOTE_ADDR: IP address of the machine that sends the program.

REMOTE_USER: name of the sender.

CONTENT_TYPE: POST, usually application/xwww-form-urlencoded.

CONTENT_LENGTH: the number of bytes of data input by the POST method.

Build a C-language CGI and Apache server Development Environment

 

The procedure is as follows:

First, you need to use these tools and code:

  • C language compiler;
  • Apache server. I use the Apache server () contained in USBWebSever. This is an AMP server package and can be used without installation. The locally installed Apche server can also be used;

Then, compile the cgi program in C language.

 

Source code: c cgi Example

Then, configure and start the Apache server.

For USB websever, modify httpd. conf in the settings directory as follows:

ScriptAlias /cgi-bin/ "{rootdir}/cgi-bin/"

<Directory "{rootdir}/cgi-bin">
#   AllowOverride All
#   Options None
    AllowOverride None
    Options ExecCGI
    Order allow,deny
    Allow from all
</Directory>
AddHandler cgi-script .exe .pl .cgi

After modification, double-click usbwebsever.exe to start the Apache server.

Copy the just-generated cgiprogram (.exe file) to the/cgi-bin/directory mentioned above. You 'd better change the file name to index. cgi. For USB websever, the cgi-bin directory should be the cgi-bin directory under the root directory (if no new one is required), rather than the cgi-bin directory under the same directory as USB websever. The directory structure is as follows:


Open the browser and enter http: // 127.0.0.1: 8080/cgi-bin/index. cgi to access the cgi program.

C cgi Example

Index.html


<head>
   <meta http-equiv = "Content-Type" content = "text / html; charset = utf-8" />
   <body>
     <form action = "/ cgi-bin / mult.cgi">
         <p> CGI form processing: Get method demonstration: input multiplier and multiplicand, calculation result </ p>
             M: <input name = "m" size = "5">
             N: <input name = "n" size = "5">
         <br> <input type = "submit" value = "OK"> </ input> </br>

     </ form>

     <form action = "/ cgi-bin / collect.cgi" method = "POST">
         <p> CGI form processing: Post method demo: Please enter your message (maximum 80 characters):
         <br> <input name = "data" size = "60" maxlength = "80"> </br>
         <input type = "SUBMIT" value = "OK">
     </ form>
    
     <form action = "/ cgi-bin / viewdata.cgi">
         <p> <input type = "SUBMIT" value = "Check the message">
     </ form>
   </ body>
</ head>



mult.cgi


#include <stdio.h>
#include <stdlib.h>
int main (void)
{
     char * data;
     long m, n;
     printf ("% s", "Content-Type: text / html \ n \ n");
     printf ("<html>");
     printf ("<head> <title> Multiplication result </ title>");
     printf ("<h3> Multiplication result </ h3>");
     printf ("</ head> <body>");
     data = getenv ("QUERY_STRING");
     if (data == NULL)
         printf ("<p> Error! Data was not entered or there was a problem with the data transmission");
     else if (sscanf (data, "m =% ld & n =% ld", & m, & n)! = 2)
         printf ("<p> Error! The input data is illegal. You must enter numbers in the form.");
     else
         printf ("<p>% ld *% ld =% ld.", m, n, m * n);
     printf ("</ body> </ html>");
     return 0;
}


Running example:
collect.cgi


 
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 80
#define EXTRA 5
 4 bytes are reserved for the field name "data", 1 byte is reserved for "="
#define MAXINPUT MAXLEN + EXTRA + 2
 1 byte for newline, and one for NULL
#define DATAFILE "../data/data.txt"
 The file to be added
void decode (char * src, char * last, char * dest)
{
    for (; src! = last; src ++, dest ++)
        if (* src == '+')
            * dest = '';
        else if (* src == '%')
        {
            int code;
            if (sscanf (src + 1, "% 2x", & code)! = 1)
                code = '?';
            * dest = code;
            src + = 2;
        }
        else
            * dest = * src;
    * dest = '\ n';
    * ++ dest = '\ 0';
}
int main (void)
{
    char * lenstr;
    char input [MAXINPUT], data [MAXINPUT];
    long len;
    printf ("% s", "Content-Type: text / html \ n \ n");
    printf ("<html> <head> <title> Response </ title>");
    printf ("</ head> <body>");
    lenstr = getenv ("CONTENT_LENGTH");
    if (lenstr == NULL || sscanf (lenstr, "% ld", & len)! = 1 || len> MAXLEN)
        printf ("<p> Form submission error");
    else
    {
        FILE * f;
        fgets (input, len + 1, stdin);
        decode (input + EXTRA, input + len, data);
        f = fopen (DATAFILE, "a");
        if (f == NULL)
            printf ("<p> Sorry, an unexpected error prevented the system from saving your message");
        else {
            fputs (data, f);
            printf ("<p> Thank you very much, your message has been received by the system");
        }

        fclose (f);

    }

    printf ("</ body> </ html>");
    return 0;
}

viewdata.cgi


#include <stdio.h>
#include <stdlib.h>
#define DATAFILE "../data/data.txt"
int main (void)
{
     FILE * f = fopen (DATAFILE, "r");
     int ch;
     if (f == NULL)
     {
         printf ("% s", "Content-Type: text / html \ n \ n");
         printf ("<P> <EM> Unexpected error, unable to open file </ EM>");
     }
     else
     {
         printf ("% s", "Content-Type: text / plain \ n \ n");
         while ((ch = getc (f))! = EOF)
             putchar (ch);
         fclose (f);
     }

     return 0;
}
Related Article

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.