Introduction to CGI programming, for how to enter the CGI;LINUX_CGI programming __ block Chain

Source: Internet
Author: User
Tags html form stdin
This article is contributed by whyang2006

The reason for this is that it requires a Web page to control peripheral hardware under Arm's Linux platform.


Why do you want to do CGI programming? In HTML, when a customer fills out a form, and press the Send button, the content of the form is sent to the server side, in general, then need to have a server-side script to the contents of the form to do some processing, or to save them, or by the content of some inquiries, or is something else. A world without cgi,web completely loses its interactivity, and all information becomes one-way, without the ability to have any feedback.


Some people think that JavaScript can be used instead of CGI programs, which is actually a conceptual error. JavaScript can only run in the client browser, while CGI is working on the server. The work they do has some intersection, such as form data validation, but JavaScript is definitely not a substitute for CGI. But it can be said that if a job can be done with JavaScript, and can be done with CGI, then the absolute use of JavaScript, at the speed of execution, JavaScript has an inherent advantage over CGI. Only those problems that cannot be resolved by the client, such as interacting with a remote database, should be used with CGI. In short, it is the interface CGI (INTERFACEZ) used to communicate HTML forms and server-side programs. Say it's an interface, which means that CGI is not a language, but a set of specifications that can be applied by other languages. In theory, you can write CGI programs in any programming language, as long as you are programmed to conform to something defined by the CGI specification.


C is one of the preferred languages for CGI programming, since C is a good platform-agnostic (with its corresponding compilers on almost any system platform) and is familiar to most programmers (unlike Perl). Here we introduce the use of C to write CGI programs. One of the simplest examples of CGI programming is the processing of forms. So in this article, we mainly introduce how to use C to write a CGI program to do the table but processing. Get form processing for those forms that use the attribute "Method=get" (or without the method attribute, the get is its default), CGI is defined as: When the form is sent to the server to judge, the data in the form is saved on the server, one called Query_string Environment variables. The processing of this form is relatively simple, as long as you read the environment variables. This is a different approach to different languages.


In C, you can use the library function getenv (defined in the standard library function Stdlib) to access the value of an environment variable as a string. You can get the data in the string and use some tricks for the type conversion, which is quite simple. Standard output in a CGI program (output) (such as the stdout file stream in C) is also redefined. It does not produce any output on the server, but is redirected to the client browser. In this way, if you write a C CGI program, export an HTML document to its stdout, the HTML document will be displayed in the client's browser. This is also a basic principle of CGI programs. Let's look at a specific program implementation, and here's an HTML form:

<form action= "/cgi-bin/mult.cgi" >
<P> please fill in the multiplier and multiplier below and click OK to see the results.
<input name= "M" size= "5" > 
<input name= "n" size= "5" >
<BR>
<input type= "SUBMIT" Value= "OK" > </FORM>

The function we want to implement is simply to multiply the values entered in the form and then output the results. In fact, this feature can be implemented entirely in JavaScript, but in order to make the program as simple as possible, I chose this small multiplication as an example. Here is the CGI program that handles this form, corresponding to the value of the ACTION attribute in the form label.
#include < stdio.h >
#include < stdlib.h >
int main (void) { 
    char *data; 
    Long M,n; 
    printf ("%s%c%c", "contentype:text/html;charset=gb2312", 13,10); 
    printf ("<TITLE> multiplication result </TITLE>"); 
    printf ("<H3> multiplication result 


The specific C syntax is not much to say, let's look at it as a special place for CGI programs. The content of the standard output mentioned above is the content to be displayed in the browser. The output of the first line is required and is also a
Characteristic of a CGI program:

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

, this output is the header of the file as HTML. Because CGI can not only output HTML text like a browser, but also output images, sounds, and so on. This line tells the browser how to handle the received content. There are two lines of blank lines behind 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.

One of the most common techniques.


The program then calls the library function getevn to get the query_string content, and then uses the SSCANF function to take out each parameter value, it is important to note the use of the SSCANF function. The other is nothing, and the general C program is no different. After compiling the program, renamed MULT.CGI placed under the/cgi-bin/directory, it can be monotonous use of the table. In this way, a CGI program that handles get form forms is done.


Post form processing Let's consider another form transfer method: Post. Let's assume that the task we are implementing is to add a piece of text that the customer entered in the form to the back of a text file on the server. This can be seen as the embryonic form of a message board program. Obviously, this job cannot be implemented using JavaScript as a client script, and is a real CGI program. It seems that the problem is similar to what is said above, simply by using different forms and different scripts (Programs). But in fact, there are some differences between the two.

In the example above, the processing of a get can be thought of as a "pure query (pure query)" type, that is, it has nothing to do with state. The same data can be submitted any number of times without causing any problems (except for some small overhead of the server) but now the task is different. At least it's going to change the content of a file. Thus, it can be said that it is related to the state. This is also considered one of the differences between POST and get. Also, get is limited to the length of the form, and post is not, which is the main reason for choosing the Post method in this task. But relatively, the process of getting is faster than POST. In the definition of CGI, the contents of a POST-type form are sent to the standard input of the CGI program (stdin in C), while the length of the transmission is placed in the environment variable CONTENT_LENGTH. So what we're going to do is read the content_length length string in the standard input.

Reading data from standard output sounds like it's easier to read data from an environment variable than it is, but otherwise, there are some details to pay attention to, which can be seen in the following program. Special attention is: CGI programs and general procedures are not, the general program after reading the contents of a file stream, you will get an EOF logo. But in the process of the CGI program form processing, EOF is never appear, so do not read more than content_length length of characters, whether this will have any consequences, no one knows (the CGI specification is not defined, generally based on the different server and have different processing methods). Let's take a look at how to collect data from the POST form to the CGI program, and here's a simpler C source code:

#include < stdio.h > #include < stdlib.h > #define MAXLEN #define EXTRA 5/* 4 bytes Left field name "Data", 1 bytes Left to "=" * * * #define MAXINPUT maxlen+extra+2/* 1 bytes left to line break, there is a left behind the null * * * * #define DATAFILE ".  /data/data.txt "/* * file to be added/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%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, unable to 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 word length of the data from the CONTENT_LENGTH environment variable, and then reads the string of corresponding lengths. Because the data content is encoded in the process of transmission, it must be decoded accordingly. The coding rules are simple, and the main ones are:

1. Each field in the form is represented by the field name followed by an equal sign, and then the value of the field is used to indicate that the content between each field is & connected;

2. All the space symbols are replaced by plus sign, so it is illegal to appear in the Code section;

3. Special characters such as punctuation marks, and some words of a particular meaning Furu "+", expressed with a percent sign followed by its corresponding acsii code value.

For example, if the user enters: Hello there!, the data is encoded when it is transmitted to the server, and it becomes the Unencode () function on the data=hello+there%21 to decode the encoded data. After the decoding is complete, the data is added to the end of the Data.txt file and is displayed back in the browse.


After compiling the file, renaming it to collect.cgi and placing it in the CGI directory can be used in a monotonous table. The corresponding form is given below:

<form action= "/cgi-bin/collect.cgi" method= "POST" > 
<P> Please enter your message (up to 80 characters):<br> <input
Name= "Data" size= "maxlength=" >
<BR> 
<input type= "SUBMIT" value= "OK" > 
</form >

As a matter of fact, this procedure can only be used as an example and cannot be formally employed. It misses a key problem: When multiple users write data like files at the same time, there is a certain error. And for one that
program, the chances of a file being written at the same time are great. Therefore, in the more formal message version of the program, you need to do some more consideration, such as adding a semaphore, or the use of a key file.

Because it's just a matter of programming skills, it's not much to say here. Finally, we're going to write a CGI program that browses the Data.txt file, which only needs to be output 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%c", "content-type:text/html;charset=gb2312", 13,10); 
        printf ("<TITLE> error </TITLE>");
        printf ("<P><EM> unexpected error, unable to open file </em >") 
    ; 
    else { 
        printf ("%s%c%c", "Content-type:text/plain", 13,10);
        while ((Ch=getc (f))!= EOF)   
            putchar (CH); 
            Fclose (f); 
     } 
     return 0; 
}


The only thing to note in this program is: it does not wrap data.txt into HTML format and then output, but directly as a simple text (plain text) output, as long as the output in the head with Text/plain type instead of text/html, the browser will be based on The Content-type type automatically chooses the corresponding processing method. To trigger this program is also very simple, because there is no data to enter, so just a button can be done:
<form action= "/cgi-bin/viewdata.cgi" > 
<P>
<input type= "SUBMIT" value= "viewing" > 
</ Form>


Here, some basic principles of writing CGI programs in C will be over. Of course, it's hard to write a good CGI program, which requires further learning of the CGI specification and some of the other CGI programming techniques. The purpose of this article is to understand the concept of CGI programming. In fact, some of the mainstream server-side scripting languages, such as asp,php,jsp, basically have most of the functionality of CGI programming, but they are actually much easier to use than CGI programming in whatever language they're using. So when it comes to server-side programming, it's common to consider using these scripting languages first. CGI is only used when they are not able to solve it, for example, to do some of the more low-level programming.

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.