How to write CGI programs

xiaoxiao2021-03-06  14

CGI's Working Principle: CGI (Common Gateway Interface) is a standard interface for a web server providing information service. By such an interface, the web server can execute the program and return the information output to the browser. Because data on the web online is static, through the CGI program can dynamically process the browser's request, such as saving the user's input information, returning the relevant information according to user information, etc. When the client sends a CGI request to the web server, the web server will determine the data to the CGI program according to the type of CGI program, generally transmitting data between the CGI program through standard input / output stream and environment variables.

CGI input and output principle

CGI input / output method: The CGI program performs input and output by standard input (stdin) and standard output (stdout), stdin and stdout are two pre-defined file pointers. You can use the file read and write function to manipulate it.

In addition, the CGI program is also entered by environment variables, but only is some common information in environment variables, and usually does not include information entered in the web page (in addition to using the GET method, by checking environment variables) Query_String is to get input data), and stdin is usually used to pass the information entered by the user. In normal CGI program development, we need to care about the environment variables:

Part of the environment variable related to the web server:

Server_name Web Server Name Server_Port Web Server Listening Address Server_Protocol Use to Send Request Protocol Names and Version Server_software Web Server Names and Versions

Part is related to running CGI:

Request_Method Data Transfer (Information Pass) Method Content_Length Data Length Query_String Data Transport Data Remote_ADDR Client IP Address Remote_host Client Host Nature

Part is related to the client:

HTTP_USER_AGENT Customer Browser Name HTTP_ACCEPT client The MIME Type list of MIME Types HTTP_REFERER The URL of the previous document in the client

POST / GET method used in input: Two methods are usually adopted when sending data to CGI: GET / post, GET method is sent to the URL, such as: /cgi/a_cgi_test.exe? Your_Data, The CGI program is entered by checking the environment variable query_string. The POST method will send the data to the STDIN input stream of the CGI program. Each variable in form (form) will become the form of Name = value to the web server, multiple data between & separated & separated, such as: name = value & name2 = value2. Where the name (name, name2) is the INPUT, SELECT, or TextArea, which defines defined in the Form, and the value is the user input or selected specified value.

With the top knowledge we can write a simple CGI program immediately. code show as below:

Void main (void)

{// This program prints out the data input by the user

FPRINTF (stdout, "content-type: text / place / n / n");

/ / Output a CGI title, this line of code will explain

CHAR * PSZMETHOD;

pszmethod = GetENV ("Request_Method");

IF (strncmp (pszmethod, "get") == 0) {// Get Method

// Read environment variables to get data

FPRINTF (stdout, "input data is: / n% s", GetENV ("Query_String"));

}

Else

{// post method

// Read stdin to get data

INT ILENGTH = ATOI (GetENV ("Content_length"));

FPRINTF (Stdout, "Input Data IS: / N");

For (int i = 0; i

{

Char cget = fgetchar (stdin);

FPUTCHAR (STDOUT, CGET);

}

}

}>

As mentioned above, a CGI title must be output when the CGI program is output, and the title is three categories:

Location: Title, specify the URL of another document, such as fprintf (stdout, "location: http://www.vchelp.net//n"); Content-Type: Title, specify the MIME type of the transmitted data For example, FPrintf (stdout, "content-type: text / html / n / n"); status: title, indicating HTTP status code, such as FPrintf (stdout, "status: 200 / n / n"); pay attention to each title Although you must follow a wrap and an empty line. The MIME type is represented in the form of type / subtype, and below is a combination of common type / subtypes:

Text / Plain Ordinary Text Type Text / HTML HTML Format Text Type Audio / Basic Outer Sound File Format, Suffix for .au Video / MPEG MPEG File Format Video / QuickTime QuickTime File Format Image / Gif GIF Graphics File Image / JPEG JPEG Graphics File image / x-xbitmap x bitmap graphics file, the suffix is. XBM has the above knowledge We can write some CGI programs, first need to analyze the input data, the method is: Whenever the character =, mark a Form The end of the variable name; whenever the character &, marking the end of a FORM variable value. Note that the value of the last variable of the input data is not to end. This way we can decompose the input data into a group of points. However, the input word symbol string of CGI will then be found, for example, sometimes the input word symbol string similar to the following format: filename = hello & cmd = world i% 27, because the browser encodes some of the top-up special characters, so Decoding after the data is decomposed, the decoding rules are: : convert into spaces;% xx: Special characters represented by its hexadecimal ASCII code value (% as a transllection). Convert it into a corresponding ASCII character based on value xx. This conversion is performed on the Form variable name and variable value. Below is a CGI program that analyzes Form data and delivers the result to the web server.

#include

#include

#include

Int htoi (char *);

Main ()

{

INT I, N;

Char C;

Printf ("ContentType: Text / PLAIN / N / N");

n = 0;

IF (GetENV ("Content-Length")))

n = atoi (GetENV ("Content-Length"));

For (i = 0; i

C = getchar ();

Switch (c) {

Case '&':

C = '/ n';

Break;

Case ' ':

C = '';

Break;

Case '%': {

Char s [3];

s [0] = getchar ();

s [1] = getChar ();

S [2] = 0;

C = HTOI (s);

i = 2;

}

Break;

CASE '=':

C = ':';

IS-EQ = 1;

Break;

}

PUTCHAR (C);

IF (IS-EQ) Putchar ('');

}

PUTCHAR ('/ n');

Fflush (stdout);

}

/ * Convert HEX STRING To INT * /

Int htoi (char * s)

{

CHAR * DIGITS = "0123456789AbcDef";

IF (Islower (s [0])) s [0] = TouPper (s [0]);

IF (Islower (s [1])) s [1] = TouPper (s [1]);

Return 16 * (Strchr (Digits, s [0]) --STRCHR (Digits, '0'))

(Strchr (Digits, S [1]) - STRCHR (Digits, '0'));

}>

The above program first outputs a MIME header to the web server, check the number of characters in the input, and cycle checks each character. When the character is the character is, it means a name / value end, the program outputs an empty line; when the character is , turn it into a space; when the character is%, it means a ten-character ten The beginning of the six-input value, call the HTOI () function to convert the subsequent two characters to the corresponding ASCII character; when the character is =, it means the end of the name / value of the name part, and convert it into character:. Finally, the converted characters will be output to the web server. The development CGI program can be performed according to the following steps: 1. Judgment the data input method is GET or POST. 2. Read the data, decompose each received form variable according to the separated symbol & to decode the data at the same time. 3, process data. 4, output the CGI title, output HTML data. 5, exit. Developing CGI using CGI requires yourself to analyze your input data, but word symbol string handles not C language strength, so I recommend a set of developments I think that I think is more good, CGIC, (by http: // www. " Boutell.com/boutell/ is free). I have a small amount of modification provided in the development package, and use the VC6 author into lib. After downloading, you can see the description provided by the development package, which is not only given an example code, but also has a detailed explanation of each function.

Part of the environment variable related to the web server:

Server_name Web Server Name Server_Port Web Server Listening Address Server_Protocol Use to Send Request Protocol Names and Version Server_software Web Server Names and Versions

Part is related to running CGI:

Request_Method Data Transfer (Information Pass) Method Content_Length Data Length Query_String Data Transport Data Remote_ADDR Client IP Address Remote_host Client Host Nature

Part is related to the client:

HTTP_USER_AGENT Customer Browser Name HTTP_ACCEPT client The MIME Type list of MIME Types HTTP_REFERER The URL of the previous document in the client

POST / GET method used in input: Two methods are usually adopted when sending data to CGI: GET / post, GET method is sent to the URL, such as: /cgi/a_cgi_test.exe? Your_Data, The CGI program is entered by checking the environment variable query_string. The POST method will send the data to the STDIN input stream of the CGI program. Each variable in form (form) will become the form of Name = value to the web server, multiple data between & separated & separated, such as: name = value & name2 = value2. Where the name (name, name2) is the INPUT, SELECT, or TextArea, which defines defined in the Form, and the value is the user input or selected specified value. With the top knowledge we can write a simple CGI program immediately. code show as below:

Void main (void)

{// This program prints out the data input by the user

FPRINTF (stdout, "content-type: text / place / n / n");

/ / Output a CGI title, this line of code will explain

CHAR * PSZMETHOD;

pszmethod = GetENV ("Request_Method");

IF (strncmp (pszmethod, "get") == 0)

{/ Get Method

// Read environment variables to get data

FPRINTF (stdout, "input data is: / n% s", GetENV ("Query_String"));

}

Else

{// post method

// Read stdin to get data

INT ILENGTH = ATOI (GetENV ("Content_length"));

FPRINTF (Stdout, "Input Data IS: / N");

For (int i = 0; i

{

Char cget = fgetchar (stdin);

FPUTCHAR (STDOUT, CGET);

}

}

}>

As mentioned above, a CGI title must be output when the CGI program is output, and the title is three categories:

Location: Title, specify the URL of another document, such as fprintf (stdout, "location: http://www.vchelp.net//n"); Content-Type: Title, specify the MIME type of the transmitted data For example, FPrintf (stdout, "content-type: text / html / n / n"); status: title, indicating HTTP status code, such as FPrintf (stdout, "status: 200 / n / n"); pay attention to each title Although you must follow a wrap and an empty line. The MIME type is represented in the form of type / subtype, and below is a combination of common type / subtypes:

Text / Plain Ordinary Text Type Text / HTML HTML Format Text Type Audio / Basic Outer Sound File Format, Suffix for .au Video / MPEG MPEG File Format Video / QuickTime QuickTime File Format Image / Gif GIF Graphics File Image / JPEG JPEG Graphics File image / x-xbitmap x bitmap graphics file, the suffix is. XBM has the above knowledge We can write some CGI programs, first need to analyze the input data, the method is: Whenever the character =, mark a Form The end of the variable name; whenever the character &, marking the end of a FORM variable value. Note that the value of the last variable of the input data is not to end. This way we can decompose the input data into a group of points. However, the input word symbol string of CGI will then be found, for example, sometimes the input word symbol string similar to the following format: filename = hello & cmd = world i% 27, because the browser encodes some of the top-up special characters, so Decoding after the data is decomposed, the decoding rules are: : convert into spaces;% xx: Special characters represented by its hexadecimal ASCII code value (% as a transllection). Convert it into a corresponding ASCII character based on value xx. This conversion is performed on the Form variable name and variable value. Below is a CGI program that analyzes Form data and delivers the result to the web server. #include

#include

#include

Int htoi (char *);

Main ()

{

INT I, N;

Char C;

Printf ("ContentType: Text / PLAIN / N / N");

n = 0;

IF (GetENV ("Content-Length")))

n = atoi (GetENV ("Content-Length"));

For (i = 0; i

INT IS-EQ = 0;

C = getchar ();

Switch (c) {

Case '&':

C = '/ n';

Break;

Case ' ':

C = '';

Break;

Case '%': {

Char s [3];

s [0] = getchar ();

s [1] = getChar ();

S [2] = 0;

C = HTOI (s);

i = 2;

}

Break;

CASE '=':

C = ':';

IS-EQ = 1;

Break;

}

PUTCHAR (C);

IF (IS-EQ) Putchar ('');

}

PUTCHAR ('/ n');

Fflush (stdout);

}

/ * Convert HEX STRING To INT * /

Int htoi (char * s)

{

CHAR * DIGITS = "0123456789AbcDef";

IF (Islower (s [0])) s [0] = TouPper (s [0]);

IF (Islower (s [1])) s [1] = TouPper (s [1]);

Return 16 * (Strchr (Digits, s [0]) --STRCHR (Digits, '0'))

(Strchr (Digits, S [1]) - STRCHR (Digits, '0'));

}>

转载请注明原文地址:https://www.9cbs.com/read-50510.html

New Post(0)