CGI programming entry, for how to enter CGI; linux_cgi Programming

Source: Internet
Author: User

This article is contributed by whyang2006

The reason for this article is that it is required to control peripheral hardware devices through the web page on the Linux platform of arm.

Why do we need CGI programming? In HTML, when the customer fills out the form and presses the send button, the content of the form is sent to the server, generally, in this case, you need a server script to process the Form Content, save them, query by content, or something else. Without CGI, the web world completely loses its interaction. All information becomes one-way, and no feedback is enough.

Some people think that the CGI program can be replaced by JavaScript, which is a conceptual error. Javascript can only run in the client browser, while cgi works on the server. Their work involves some intersections, such as form data verification, but JavaScript cannot replace CGI. But it can be said that if a job can be done with JavaScript and CGI, JavaScript is definitely used. In terms of execution speed, JavaScript has a inherent advantage over CGI. Only problems that cannot be solved on the client, such
Data library interaction, then CGI should be used. To put it simply, it is used to communicate with the interface CGI (interfacez) of HTML forms and server programs. It is an interface, that is, CGI is not a language, but a set of specifications that can be applied by other languages. In theory, you can use any programming language to compile CGI programs, as long as the programs comply with the CGI specifications defined in some of them.

The C language performs well in terms of platform independence (almost any system platform has its corresponding compiler) and is quite familiar to most programmers (unlike Perl ), therefore, C is one of the preferred languages for CGI programming. Here we will introduce how to use C to write CGI programs. The simplest example of CGI programming is form processing. Therefore, in this article, we mainly introduce how to use C to write CGI programs for table processing. Get form processing for those forms that use the property "method = get" (or do not have the method property, then get is the default value), CGI
It is defined as: After the form is sent to the server for judgment, the data in the form is saved in an environment variable called QUERY_STRING on the server. The processing of such forms is relatively simple. You only need to read the environment variables. This is different for different languages.

In C, you can use the library function getenv (defined in the standard library function stdlib) to access the environment variable value as a string. After obtaining the data in the string, you can use some tips to perform type conversion, which is relatively simple. The standard output in the CGI program (such as the stdout file stream in C) is also redefined. It does not produce any output content on the server, but is redirected to the client browser. In this way, if you write a c cgi program and output an HTML document to its stdout, the HTML document will be
The user's browser is displayed. This is also a basic principle of CGI programs. Let's take a look at the specific program implementation. The following is an HTML form:

<Form action = "/cgi-bin/mult. cgi"> <p> enter the multiplier and the multiplier below. Press OK to see the result. <Input name = "M" size = "5"> <input name = "N" size = "5"> <br> <input type = "Submit" value = "OK "> </form>

The function we need to implement is very simple, that is, to multiply the input values in the form and then output the result. In fact, this function can be fully implemented using JavaScript, but in order to make the program as simple as possible, I chose this small multiplication as an example. The following is the CGI program that processes the form, which corresponds to the action attribute value in the form tag.

# Include <stdio. h> # include <stdlib. h> int main (void) {char * data; long M, N; printf ("% S % C", "contentype: text/html; charset = gb2312 ", 13, 10); printf ("<title> multiplication result </title>"); printf ("

The specific c syntax will not be discussed much. Let's look at it as a special place for CGI programs. As mentioned above, the standard output content is to be displayed in the browser. The output content of the first line is required and
Unique CGI program:

printf("%s%c%c ","Content-Type:text/html",13,10);

The output is the HTML file header. CGI not only outputs HTML text like a browser, but also outputs images, sounds, and other things. This line tells the browser how to handle the received content. There are two blank rows after the definition of Content-Type, which is also indispensable. Because the head output of all CGI programs is similar, you can define a function for it to save programming time. This is CGI programming

A common technique.

The program then calls the library function getevn to obtain the QUERY_STRING content, and then uses the sscanf function to obtain each parameter value. Note the usage of the sscanf function. Nothing else. It is no different from general C Programs. After the program is compiled, it is renamed mult. cgi and placed under the/cgi-bin/directory to be called by the form. In this way, a CGI program that processes the get form will be finished.

For post form processing, we will consider another form transfer method: Post. Let's assume that the task we want to implement is like this: add the text content entered by the customer in the form to the back of a text file on the server. This can be seen as the prototype of a message board program. Obviously, this job cannot be implemented using a client script such as JavaScript, and it is also considered a real CGI program. It seems that this question is very similar to the content mentioned above, just using different forms and different scripts (programs. But in fact, there are some differences between them.

In the above example, the get processing method can be considered as a "Pure query" type, that is, it has nothing to do with the status. The same data can be submitted at any number of times without causing any problems (except for some small overhead of the server), but the current tasks are different ,. At least it needs to change the content of a file. Therefore, it can be said that it is related to the status. This is also one of the differences between post and get. Besides, get imposes restrictions on the form length, whereas post does not. This is also the main reason for choosing the POST method in this task. However, the get processing speed is faster than that of post. In
In CGI definition, the content of a post-type form is sent to the standard input (stdin in C) of the CGI program ), the transmitted length is placed in the environment variable content_length. Therefore, we need to read the content_length string in the standard input.

Reading data from the standard output seems easier than reading data from the environment variables. In fact, it is not. Pay attention to some details, this can be seen in the following program. Note that the CGI program is different from the general program. The general program will get an EOF mark after reading the content of a file stream. However, in the form processing process of CGI programs, EOF will never appear, so do not read more characters than content_length. Otherwise, what will happen, no one knows (the CGI specification is not defined. Generally, there are different solutions based on different servers ). Let's take a look at how the post
The form collects data to the CGI program. A simple C source code is provided below:

# Include <stdio. h> # include <stdlib. h> # define maxlen 80 # define extra 5/* 4 bytes left the field name "data ", leave one byte to "=" */# define maxinput maxlen + extra + 2/* 1 byte to the line break, and a null */# define datafile ".. /data/data.txt "/* file for adding data */void unencode (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 =" "; * ++ DEST = "";}} int main (void) {char * lenstr; char input [maxinput], data [maxinput]; long Len; printf ("% S % C", "Content-Type: text/html; charset = gb2312 ", 13, 10); printf (" <title> response </title> "); 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 ); unencode (input + extra, input + Len, data); F = fopen (datafile, "A"); If (F = NULL) printf ("<p> sorry, unexpected error, cannot save your data "); else fputs (data, f); fclose (f); printf (" <p> Thank you very much, your data has been saved <br> % s ", data) ;}return 0 ;}

In essence, the program first obtains the data length from the content_length environment variable, and then reads the corresponding length string. Because the data content is encoded during transmission, it must be decoded accordingly. The encoding rules are very simple, mainly including the following:

1. Each field in the form is indicated by a field name followed by an equal sign, followed by the value of this field, and the content between each field is linked;

2. All space characters are replaced by the plus sign, so spaces in the encoding code segment are invalid;

3. Special characters, such as punctuation marks, and special characters such as "+", are expressed by the percentage followed by the corresponding acsii value.

For example, if the user inputs hello there! Then, when the data is transmitted to the server, it becomes the unencode () function above data = Hello + there % 21, which is used to decode the encoded data. After decoding, the data is added to the end of the data.txt file and displayed in the browser.

After the file is compiled, change it to collect. cgi and put it in the CGI directory to be called by the form. The corresponding form is given below:

<Form action = "/cgi-bin/collect. cgi "method =" Post "> <p> enter your message (up to 80 characters ): <br> <input name = "data" size = "60" maxlength = "80"> <br> <input type = "Submit" value = "OK"> </Form>

In fact, this program can only be used as an example and cannot be officially used. It misses a key issue: when multiple users write data like a file at the same time, there will certainly be errors. For

For example, the probability that a file is written at the same time is very high. Therefore, more considerations need to be taken into account in a relatively formal language Edition program, such as adding a semaphore or using a key file.

This is just a matter of programming skills. Finally, let's write a CGI program that browses the data.txt file. You only need to output the content to stdout:

# 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 % C", "Content-Type: text/html; charset = gb2312", 13, 10 ); printf ("<title> error </title>"); printf ("<p> <em> Unexpected error, file cannot be opened </em> ");} else {printf ("% S % C", "Content-Type: text/plain", 13, 10); While (CH = GETC (F ))! = EOF) putchar (CH); fclose (f);} return 0 ;}

The only thing to note about this program is that it does not pack data.txt into HTML format and then output it directly as a simple text (plain text, in this case, you only need to replace text/html with the text/plain type in the output header. the browser automatically selects the corresponding processing method based on the Content-Type type. It is easy to trigger this program. Because there is no data to input, you only need a button to do it:

<Form action = "/cgi-bin/viewdata. cgi"> <p> <input type = "Submit" value = ""> </form>

Here, some basic principles of writing CGI programs in C will be completed. Of course, it is difficult to compile a good CGI program based on the above content. This requires further study of the CGI standard definition and some other unique CGI programming skills. The purpose of this article is to understand the concept of CGI programming. In fact, some mainstream server-side scripting languages, such as ASP, PHP, and JSP, basically have most of the CGI programming functions, but what they are using is indeed much easier than using CGI programming in whatever language. Therefore, when programming on the server side, these scripts are generally used first.
This programming language.

CGI is used only when they cannot solve the problem, for example, when some underlying programming is required.

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.