📄 如何用c语言写cgi(1).txt
字号:
作者:hooke
日期:2001-2-28 0:35:20
CGI Scripting in C
Last Modified on 4/28/96
So you've created that perfect Fill out Form, loaded into Netscape, filled it out and pressed [Submit]. What happens next? The purpose of this page is to present a beginner's tutorial on writing CGI scripts in C. The main purpose of this is to handle forms. However, as I learn more about writing CGI scripts myself, I plan to add to this tutorial in order to show how to write counters, etc.
What this tutorial is NOT
This tutorial is not intended to be extremely technical in nature. It is also not definitive. It is based on my very limited knowledge of CGI and C programming. There are plenty of sites around which offer more technical explanations of how CGI works. Expect to find no library of custom functions which can perform actions, simple or complex, which you can then put together to form your own script.
What this tutorial IS
This tutorial is to help the beginner write your own scripts in CGI. It should help you to have a basic understanding of what CGI is, does, etc. It does present a couple of very simple scripts that I have written. The real jewel here is that I will explain these scripts line by line using only standard ANSI C header files. Unlike some other tutorials, I don't "black box" the code into some custom fuction call which you need a custom library installed to use. The source code presented here should be portable to most systems.
Recent Changes!
I have recently written some code which I think might be useful for processing Fill out Forms online or offline! They are tacked on at the end here. If you like them, send me email and tell me how you are using them. If you really like them, the going rate is some coffee. (Thanks, Ronan!)
What is CGI anyway?
CGI stands for Common Gateway Interface. Essentaily what CGI allows you to do is to run an executable program on your HTTP server. Some of the reasons why you would want to do this are:
To process data submitted from a Fill Out Form
To create a custom HTML document on the fly
To run a counter (such as "42405 people have accessed this page since...")
To process data from an image map
If you don't want to do any of the above, you probably don't need to worry about CGI. However, many people are interested in using Fill Out Forms. Why? They are cool. You can create things like a guestbook, polls, or conduct survey research. If this sounds like you, continue!
What language are CGI scripts written in anyway?
CGI scripts can be written in any language which produces an executable file which can run on your server. CGI scripts are often written in Perl, Unix Shell, AppleScript (especially on Macintosh Servers), or C. However, these are not your only options. However, this tutorial deals exclusively with C. Why? Because I write in C and I don't know anything about any of these other languages. (I can write in Forth, BASIC, and NewtonScript too, but I think C is a better choice for writing CGI scripts because it is portable.)
Okay, I'm ready to begin. What do I need?
Here's what I am assuming about you:
you have at least a passing knowledge of C
you have a web server that you can run scripts from
you already know how to create Fill Out Forms
you have some type of ANSI compliant C compiler
Let's Begin!
When you created your fill out forms, you used code that went something like this:
<FORM ACTION="http://www.domain.xxx/~me/myscript.exe" METHOD=POST>
If you didn't, you should have. This is the point at which you call your script and specify how the data will be sent to the server. You should probably use the POST method. This tutorial will assume that you are using the POST method. Why? The GET method (your other option) appends the data from your form onto the end of the end of an environmental variable called "QUERY_STRING". POST allows you to read the contents of your form from stdin. This is more elegant. The data which is sent by the client to the server takes the following form:
variable1=value&checkbox=on&input_line=Hello,+how+are+you?&...
As you can see, different types of variables are represented differently depending on what they are. For example Select varaibles are represented as name=value. Checkboxes, on the other hand are included only if they are checked and in that case represented as name_of_checkbox=on (if it isn't there, the value is off.) The different variables are seperated by ampersands (&s).
How do I get this data?
The form data, as was previously stated, can be read from stdin. You don't need to worry about setting stdin to point to the right place or anything. Just start reading from stdin. How big is the data stream? How much do I read? This information is passed to you in the form of an Enviornmental Variable called "CONTENT_LENGTH".
What's an Environmental Variable?
An enironmental variable is a variable which exists in the environment that the program is running in (i.e. at some memory location in the machine). They are put there by the server software. The important thing about environmental variables is that you can use them. The getenv() function call is used to retrive a char pointer to an environmental variable. Here's an example of getenv():
const char *str_len = getenv("CONTENT_LENGTH");
This line declares a const char pointer called str_len and makes it point to the location of CONTENT_LENGTH. So far, so good. However, you would ideally like CONTENT_LENGTH to be a variable of type int, not some const char pointer. Why? Simple. You can't use a const char pointer in a for loop. Here's a line which converts this to type double:
length = strtod ( str_len, NULL);
Be sure to declare length as a double. This is better. You can now use length in a for loop to read the data from the client into an array.
for(i=0;i<length;i++)
{
fscanf(stdin, "%c", &DATA[i]);
}
Again, be sure to declare your variables (in this case the array DATA[] and i).
How can I be sure that I'm with you so far?
At this point, it might be advisable to try running the first of the two simple scripts I have here just to be certain that you know what you are doing. Some servers require that CGI scripts exist in a particular directory and/or be called by a URL in a particular way. One of the reasons for this is that on many Unix and VMS servers, your script runs as if you are running an executable file from your shell account (i.e. under your userid). Thus requiring the URL to be called in a certain way. Again, I assume that you have created your first Fill Out Form and have it loaded onto your server. Try compiling the following program and running it from your Form. (If you have problems getting the script to run at all talk to your Web Precence Provider.)
main()
{
int i;
char data[1000]; /* this will work for forms that are not really, really long. If you have an error due to
writing off the end of the array, try increasing the array size. */
double length;
const char *str_len=genenv("CONTENT_LENGTH");
length=strtod(str_len, NULL);
for(i=0;i<length;i++)
{
fscanf(stdin, "%c", &DATA[i]);
}
printf("Content-type: text/html\n\n"); /* this line tells the client that it is recieving a document of type text/html meaning an HTML document. The two returns are necessary. Always put them in if you are creating a document with your script (even if it is a different type)*/
printf("%s\n", DATA); /*This sends the string to the client. When you run the script from your browser, you should see the raw data that your entered appear on your screen. You can also send any other text you desire this way.*/
You can link to a text version of this script or try it out on my server using a simple Form.
Okay, that's working so far, but I want to write a real script that I could really use.
The next tweak to the script will do the following:
save the data to a file rather than printing it to the screen
return a location rather than an HTML document (if you had any doubts, the last script created an HTML document on the fly consisting of the the data stream read from stdin)
In order to save the data to a script, first we must create a file pointer and make it point to a file:
FILE *filepointer; /* declare a file pointer */
if ((filepointer=fopen("ourdatafile.dat", "a"))==NULL)
{
printf("Content-type: text/html\n\n Sorry. There is a problem. Please try using the form again later.\n");
exit(1);
}
/* This opens our data file so that we can append our data onto the end of it. If the file doesn't exist, it will be created. If, for some reason, the file cannot be opened, an apology is returned to the user. */
Now, we use fprintf to save our data:
fprintf(filepointer,"%s\n", DATA);
and return a location to the user:
printf("Location: http://www.domain.xxx/doc_we_are_returning.html");
You can view this entire script as a text file.
Processing Form Data!!!
Alright, what if you want to decode and use this data for stuff? I have written a couple of useful functions which might help. The name of the function is get_var. get_var takes three arguments. The first of these is a constant character pointer to the input stream. However, you cannot send stdin to the function. The first step is copying stdin to an array. Following this, you need to add an ampersand (&)to the end of the array. You can do this with the following code which you should have towards the beginning of main() (before you call get_var):
scanf("%s", &stream);
stream[strlen(stream)]= '&';
..where stream has been previously defined as an array of adequate length (whatever you think that is). You could also dynamically allocate stream. However, I haven't done that yet.
So get_var takes a pointer (of type const char) to the stream you are decoding from. The second argument is a pointer to an array of type char which is the destination for the value of your variable. The third argument is a pointer to a string of type const char which is the name of the variable you want to decode along with an equal sign (=). So, a typical call to get_var() might look like this. If stream is the form data (an array) and VarOne is the destination (again, an array), and your variable is called "var_one" in your form, this is the call:
get_var(stream, VarOne, "var_one");
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -