之前沒有真正寫過CGI.只有用過類似PHP, ASP的開發環境.所以其實對GET/POST的差異性,並沒有扎實的概念.現在玩了一下,就更清楚網頁運作的過程.
The HTML specifications technically
define the difference between
"GET"
and "POST"
so that former means that
form data is to be encoded (by a browser) into a
URL while the latter means that the form data is to appear
within a message body.
As a simplification, we might say that
"GET"
is basically for just getting (retrieving) data
whereas "POST"
may involve anything, like
storing or updating data, or ordering a product, or sending E-mail.
In principle, processing of a submitted form data depends on
whether it is sent with METHOD="GET"
or
METHOD="POST"
. Since the data is encoded
in different ways, different decoding mechanisms are needed.
Thus, generally speaking, changing the METHOD
may necessitate
a change in the script which processes the submission.
For example,
when using the CGI interface,
the script receives the data in an environment variable
when METHOD="GET"
is used but in the standard
input stream (stdin
) when METHOD="POST"
is used.
文中敘述到,POST是透過stdin的輸入處理,而GET就是透過環境變數QUERY_STRING取得.
從網路找到一個處理http parameter的函式,缺點是沒有很安全,且POST資源的很weak.所以還是要修改記憶體使用的問題.
把它當作header檔案,再CGI中引入,並呼叫getAllParams()初始化該工具. 接著就可以用getParam()取得想要的參數.
// Helper macro to convert two-character hex strings to character value #define ToHex(Y) (Y>='0'&&Y<='9'?Y-'0':Y-'A'+10) static char InputData[4096]; static void getAllParams() { // Determing if it is a POST or GET method if( getenv( "REQUEST_METHOD" ) == 0 ) { printf("No REQUEST_METHOD, must be running in DOS mode"); return; } else if (strcmp( getenv("REQUEST_METHOD"), "POST") == 0) { // If POST, but don't support multipart form char *endptr; // quite useless, but required char *len1 = getenv("CONTENT_LENGTH"); int contentlength = strtol(len1, &endptr, 10); fread(InputData , contentlength, 1, stdin); } else { // If GET strncpy(InputData, getenv("QUERY_STRING"), sizeof(InputData)); InputData[sizeof(InputData)-1] = 0; } } static int getParam(const char *Name, char *Value) { char *pos1 = strstr(InputData, Name); if (pos1) { pos1 += strlen(Name); // Make sure there is an '=' where we expect it if (*pos1 == '=') { pos1++; while (*pos1 && *pos1 != '&') { // Convert it to a single ASCII character and store at our Valueination if (*pos1 == '%') { *Value++ = (char)ToHex(pos1[1]) * 16 + ToHex(pos1[2]); pos1 += 3; } // If it's a '+', store a space at our Valueination else if( *pos1 == '+' ) { *Value++ = ' '; pos1++; } else { // Otherwise, just store the character at our Valueination *Value++ = *pos1++; } } *Value++ = '\0'; return 0; } } // If param not found, then use default parameter strcpy(Value, "undefine"); return -1; } /* int main() { char myName[100] = ""; char myAddress[100] = ""; printf("Content-Type:text/html \n\n"); getAllParams(); getParam("Name", myName); getParam("Address", myAddress); printf("QueryString: %s", InputData); printf("<br>"); printf("Name: %s", myName); printf("<br>"); printf("Address: %s", myAddress); return 0; } */
留言列表