CGI C language Entry __c language

Source: Internet
Author: User
Tags html form stdin
CGI C language article
Source: Chinaunix Blog Date: 2008.06.18 15:57 (total 0 reviews) I want to comment
Why do you want to do CGI programming?
  
In HTML, when a customer fills out a form and presses the Send button, the contents of the form are sent to the server side, and in general, a server-side script is required to
Content to do some processing, or to save them, or to do some query by content, or something else. Without the Cgi,web the world would have completely lost its interactivity, all the letters
The interest is one-way, and no feedback can be made.
  
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, but CGI works in
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 is sufficient
JavaScript to do, and can do with CGI, then absolutely to use JavaScript, at the speed of execution, JavaScript has a natural advantage over CGI. Only
There are problems that cannot be resolved by the client, such as interacting with a remote database, where CGI should be used.
  
In short, CGI is the interface used to communicate HTML forms and server-side programs (interface). Say it's an interface, which means that CGI is not a language, but can be used by other languages
A set of specifications that are applied. 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. Because C language is not in the platform
A good performance (almost any system platform with its corresponding compiler), and for most programmers is very familiar (unlike Perl), so, C is the preferred language of CGI programming
One. 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.
Processing of Get Forms
 
 
For those forms that use the attribute "Method=get" (or without the method attribute, the get is its default value), the CGI definition is: When the form is sent to the server, the table
The data in the order is stored on the server in an environment variable called query_string. The processing of this form is relatively simple, as long as you read the environment variables. This point on different languages there is no
The same approach. 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 a string of
After the data, the use of some small techniques for type conversion, this is relatively simple. Standard output in a CGI program (output) (such as the stdout file stream in C) is also a reset
Righteousness. It does not produce any output on the server, but is redirected to the client browser. So, if you write a C CGI program, export an HTML document to its
On stdout, this HTML document is 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:

Please fill in the multiplier and the multiplier below and click OK to see the result.




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
#include
int main (void)
{
Char *data;
Long M,n;
printf ("%s%c%c", "content-type:text/html;charset=gb2312", 13,10);
printf ("multiplication result");
printf ("multiplication result");
data = getenv ("query_string");
if (data = NULL)
printf ("error.") Data not being entered or having a data transfer problem ");
else if (sscanf (data, "M=%ld&n=%ld", &m,&n)!=2)
printf ("error.") The input data is illegal. A number must be entered in a form. ");
Else
The result of printf ("%ld and%ld" is:%ld.) ", m,n,m*n);
return 0;
}
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 unique to 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,
And you can output images, sounds, things like that. 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
For all CGI programs, the header output is similar, so you can define a function for it to save programming time. This is a common technique for CGI programming.
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
 
 
Here's another way to consider form transfer: 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 a prototype of the message version of the 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 approach to get
Can be considered as a "pure query" (pure
query), which means that it has nothing to do with the state. The same data can be submitted any number of times without causing any problems (except for some small overhead of the server). But the task now
is different, at least it will 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, this is the main reason to select the Post method in this task. But relatively, the process of getting is faster than post.
  
In the definition of CGI, for post-type forms, the content is sent to the standard input of the CGI program (stdin in C), while the length of the transmission is placed in the environment variable
In 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 more like a
It is easier to read data in environment variables, but otherwise, there are some details to note, which can be seen in the following program. In particular, it is important to note that CGI programs and general procedures do not
The same, general program after reading the contents of a file stream, you will get an EOF logo. But in the process of the CGI program's form processing, EOF is never going to appear, so don't read more than
Content_length the length of the character, no one will have any consequences, who do not know (the CGI specification is not defined, generally depending on the 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
#include
#define MAXLEN 80
#define EXTRA 5
/* 4 bytes left to the field name "Data", 1 bytes Left "=" * *
#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 to the 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%c",
"content-type:text/html;charset=gb2312", 13,10);
printf ("Response");
Lenstr = getenv ("Content_length");
if (lenstr = NULL | | sscanf (LENSTR, "%ld", &len)!=1 | | len > MaxLen)
printf ("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 ("Sorry, unexpected error, unable to save your data");
Else
Fputs (data, f);
Fclose (f);
printf ("Thank you very much, your data has been saved%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!
When the data is transmitted to the server, it is encoded, and the Unencode () function on the data=hello+there%21 is used 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:

Please enter your message (up to 80 characters):


 
 
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 such
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
Wait 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
#include
#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 ("error");
printf ("Unexpected error, unable to open file"); }
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 about this program is that it does not wrap the Data.txt in HTML format and then output it, but rather as a straightforward text (plain
Text) output, which as long as the output in the head with the Text/plain type instead of text/html, the browser will be based on the type of Content-type automatically selected
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:



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 are basically equipped with CGI
Most of the functions of programming, but they are in use, is more than no matter what language to do CGI programming is much easier. So when it comes to server-side programming, it's usually the first to consider using these feet
This programming language. 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.