CGI (Universal Gateway Interface)

Source: Internet
Author: User
Tags file url

Public Gateway Interface

CGI (Common Gateway Interface) is one of the most important technologies in WWW technology, which has irreplaceable important position. CGI is an interface standard between an external application (CGI program) and a Web server, and is a discipline for passing information between CGI programs and Web servers. The CGI specification allows the Web server to execute external programs and send their output to a Web browser, CGI turning a simple set of static hypermedia documents from the Web into a complete new interactive media.

Common Gateway Interface, referred to as CGI. Is physically a program that runs on the server and provides an interface to the client's HTML page. That's probably not a good idea. So let's look at a real-world example: most of today's personal pages have a message book. The work of the message book is this: the user first input some information, such as the name of things. Then the user click on the "message" (so far at the client), the browser transmits this information to the server's CGI directory in a specific CGI program, so the CGI program on the server according to a predetermined method to process. In this case, the information submitted by the user is stored in the specified file. The CGI program then sends a message to the client indicating that the requested task has ended. At this point the user will see the word "End of message" in the browser. The whole process is over.

Function

The vast majority of CGI programs are used to interpret the input information from the form, to generate the appropriate processing on the server, or to feed the corresponding feedback to the browser. CGI programs make Web pages interactive. Process steps

⑴ sends user requests to the Web server over the Internet.

The ⑵web server receives the user request and gives it to the CGI program for processing.

The ⑶CGI program transmits the processing results to the Web server.

The ⑷web server sends the results back to the user. Server Configuration

CGI programs are not placed on the server to run smoothly, if you want to make it run smoothly on the server and accurately handle the user's request, you need to use the server to make the necessary settings.

Configuration: The CGI program is placed in a particular directory or with a specific extension based on the type of server being used and its settings.

Configuration of the ⑴cren format server:

Edit the configuration file for the Cren format server (typically/etc/httpd.conf) in the file by adding: Exec cgi-bin/*/home/www/cgi-bin/*.exec. The first parameter that appears in the command cgi-bin/* indicates the name of the directory 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 true path of the CGI program directory placed in the system.

The CGI directory can be placed in the same directory as the network file or in other directories in the system, but it must be guaranteed to have the same directory in your system. After the server has been set up, the server must be restarted (unless the HTTP server is started with inetd).

Configuration of the ⑵NCSA format server

There are two ways to set up on the NCSA format server:

① in the srm.conf file (usually in the Conf directory): Script alias/cgi-bin/cgi-bin/. The Script alias command states that a file under a directory is an executable program, and that the command is used to execute these programs; The two parameters of this command are the same as the parameters of the EXEC command in the CERN format server.

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

After you set up the server in one of these methods, you have to restart the server (unless the HTTP server is started with inetd). Writing languages

CGI can be written in any language, as long as the language has standard input, output, and environment variables. For beginners, it is best to use a language that is easy to archive and represents a large number of data structures, such as in a UNIX environment:

· Perl (Practical Extraction and report Language)

· Bourne Shell or Tcl (Tool Command Language)

· PHP (hypertext Preprocessor))

Because C language has a strong platform-independent, it is also the first choice to write CGI programs.

In the Windows environment:

· C and C + +

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

Eventually Perl became the mainstream CGI language because of its cross-operating system and easy to modify features, so that the general "CGI program" was a Perl program.

List of environment variables

SERVER_NAME: Run CGI sequence as machine name or IP address.

Types of SERVER_INTERFACE:WWW servers, such as the CERN or NCSA type.

Server_protocol: Communication protocol, should be http/1.0.

Server_port:tcp Port, the Web port is generally 80.

Http_accept:http defines the type of data that the browser can accept.

Http_referer: The file URL of the sending form. (Not all browsers transmit this variable)

Http_user-agent: Information about the browser that sent the form.

GETWAY_INTERFACE:CGI version of the program, under UNIX for cgi/1.1.

The actual path name contained in the Path_translated:path_info.

Path_info: An additional path when the browser sends data by using GET mode.

The path name of the SCRIPT_NAME:CGI program.

Query_string: The data entered by the form, the content after the question mark in the URL.

Remote_host: the hostname of the sender, the value cannot be determined.

REMOTE_ADDR: The IP address of the machine that sent the program.

Remote_user: The name of the sender of the program.

Content_type:post sent, generally for application/xwww-form-urlencoded.

The number of bytes of data entered by the Content_length:post method.

Build a development environment for C-language CGI and Apache servers

The steps are as follows:

first, the tools and code that you need to use:

    • C language compiler;
    • Apache server, I use the usbwebsever included in the Apache Server (), which is an amp server suite, not installed to use, and locally installed Apche server can also be used;

Next, compile the C-language CGI program.

The source code is as follows: C CGI Example

then, configure and start the Apache server.

For Usbwebsever, modify the following contents of the httpd.conf in the settings directory as follows:

scriptalias/cgi-bin/"{rootdir}/cgi-bin/""{rootdir}/cgi-bin">#   allowoverride all#   Options None    allowoverride none    options execcgi    Orderallow,deny allow from    all</ Directory>addhandler cgi-script. exe. pl. CGI

Once modified, double-click USBWebSever.exe to start the Apache server.

Finally, the CGI program (. exe file) that you just generated is copied to the/cgi-bin/directory mentioned above, and the file name is best changed to index.cgi form. For the Usbwebsever,cgi-bin directory, it should be the Cgi-bin directory under the root directory (if you do not want to create a new one), not the Cgi-bin directory under the same directory as Usbwebsever. The directory structure is as follows:

You can access the CGI program by opening the browser input http://127.0.0.1:8080/cgi-bin/index.cgi.

C CGI Example

Index.html

<Head>  <Metahttp-equiv= "Content-type"content= "Text/html;charset=utf-8" />  <Body>    <formAction= "/cgi-bin/mult.cgi">        <P>CGI form processing: Get method Demo: Input multiplier and multiplier, calculate result</P>M:<inputname= "M"size= "5">N:<inputname= "n"size= "5">        <BR><inputtype= "Submit"value= "OK"></input></BR>    </form>    <formAction= "/cgi-bin/collect.cgi"Method= "POST" >        <P>CGI Form Processing: Post Method Demo: Please enter your message (up to 80 characters):<BR><inputname= "Data"size= "$"maxlength= "a"></BR>        <inputtype= "SUBMIT"value= "OK">    </form>         <formAction= "/cgi-bin/viewdata.cgi">        <P><inputtype= "SUBMIT"value= "View Message">    </form>  </Body></Head>

mult.cgi

#include <stdio.h>#include<stdlib.h>intMainvoid){    Char*data; Longm, N; printf ("%s","content-type:text/html\n\n"); printf (""); printf (""); printf (""); printf (""); Data= Getenv ("query_string"); if(Data = =NULL) printf ("<p> Error! Data is not being entered or transmission is problematic"); Else if(SSCANF (data,"m=%ld&n=%ld", &m, &n)! =2) printf ("<p> Error! Invalid input data. A number must be entered in the form. "); Elseprintf ("<p>%ld *%ld =%ld. ", M, N, M *N); printf ("</body>"); return 0;}

To run the example:

collect.cgi

#include <stdio.h>#include<stdlib.h>#defineMaxLen 80#defineEXTRA 54 bytes left to the name of a field"Data", 1 bytes Left"="#defineMaxinput maxlen+extra+21 bytes for line breaks, and one left for the trailing null#defineDataFile ". /data/data.txt "the file to be added datavoidDecodeChar*SRC,Char*last,Char*dest) {     for(; src! = last; src++, dest++)        if(*SRC = ='+')            *dest =' '; Else if(*SRC = ='%')        {            intCode; if(SSCANF (src +1,"%2x", &code)! =1) Code='?'; *dest =Code; SRC+=2; }        Else*dest = *src; *dest ='\ n'; *++dest =' /';}intMainvoid){    Char*Lenstr; CharInput[maxinput], data[maxinput]; LongLen; printf ("%s","content-type:text/html\n\n"); printf (""); printf (""); Lenstr= Getenv ("content_length"); if(lenstr = = NULL | | sscanf (LENSTR,"%ld", &len)! =1|| Len>maxlen) printf ("<p> form submission Errors"); Else{FILE*F; Fgets (input, Len+1, stdin); Decode (Input+ EXTRA, input +len, data); F= fopen (DataFile,"a"); if(f = =NULL) printf ("<p> Sorry, the system cannot save your message because of an unexpected error"); Else{fputs (data, f); printf ("<p> Thank you very much, your message has been received by the system");    } fclose (f); } printf ("</body>"); return 0;}

To run the example:

viewdata.cgi

#include <stdio.h>#include<stdlib.h>#defineDataFile ". /data/data.txt "intMainvoid) {FILE*f = fopen (datafile,"R"); intch; 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;}

To run the example:

CGI (Universal Gateway Interface)

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.