用c语言写了个cgi脚本,用来读取从网页中输入的字符串,并将该字符串append到本地的一个文本文件data.txt中;
cgi脚本如下,collect.c源文件:
#include <stdio.h> #include <stdlib.h> #define MAXLEN 80 /* 4 for field name "data", 1 for "=" */ #define EXTRA 5 /* 1 for added line break, 1 for trailing NUL */ #define MAXINPUT MAXLEN+EXTRA+2 #define DATAFILE "./data.txt" 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 = '\n'; *++dest = '\0'; } int main(void) { char *lenstr; char input[MAXINPUT]; char data[MAXINPUT]; long len; printf("%s%c%c\n", "Content-Type:text/html;charset=iso-8859-1",13,10); printf("<TITLE>Response</TITLE>\n"); lenstr = getenv("CONTENT_LENGTH"); if (lenstr == NULL || sscanf(lenstr,"%ld",&len) != 1 || len > MAXLEN) { printf("<P>Error in invocation - wrong FORM probably.\n"); } else { printf("<p>CONTENT_LENGTH is %ld.</p>\n", len); // fgets(input, len+1, stdin); fgets(input, len+1, stdin); unencode(input+EXTRA, input+len, data); FILE *fp; fp = fopen(DATAFILE, "a+"); if(fp == NULL) { printf("<p>Sorry, cannot store your data.</p>"); } else { printf("<p>Your data is: %s.</p>\n", data); fputs(data, fp); } fclose(fp); printf("<p>Thank you! The following contribution of yours has been stored:</br></p>%s\n",data); } return 0; }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <!--meta http-equiv="charset" content="utf-8"--> <meta http-equiv="expires" content="31 Dec 2014"> </head> <body> <FORM ACTION="http://127.0.0.1/cgi-bin/collect.cgi" METHOD="POST"> <h3>Please input your words: </h3> <!--请输入您的留言(最多80个字符):--> <INPUT NAME="data" SIZE="60" MAXLENGTH="80"></br> </p> <INPUT TYPE="SUBMIT" VALUE="Ok"> </FORM> </body> </html>
使用thttpd作为web服务器提供web访问服务。
页面中的内容如下图所示:
1. 首先检查脚本collect.c,在命令行中运行编译生成的collect.cgi:
u1204@u1204-zhw:/usr/local/www/data/cgi-bin$ ./collect.cgi Content-Type:text/html;charset=iso-8859-1 <TITLE>Response</TITLE> <P>Error in invocation - wrong FORM probably. u1204@u1204-zhw:/usr/local/www/data/cgi-bin$
2. 将collect.c中对本地文件的访问屏蔽掉:
/// FILE *fp; /// // fgets(input, len+1, stdin); /// /// fgets(input, len, stdin); /// // unencode(input+EXTRA, input+len, data); /// fp = fopen(DATAFILE, "a+"); /// if (fp == NULL) { /// printf("<p>Sorry, cannot store your data.</p>"); /// } /// else { /// char tch[] = "How are you!\n"; /// fputs(tch, fp); /// } /// fclose(fp);重新编译生成collect.cgi,在网页中点击“OK”按钮。可以看到不再有“No data received”的错误提示。
提示收到了一定数量的字符串。
3. 又经过一番折腾,将本地文件data.txt的属性由664改为666,再次点击网页中的“Ok”按钮,终于可以正确显示数据了。
查看本地文件data.txt,发现网页中输入的字符串也正确追加进来了。
注意:该本地文件data.txt需要放到cgi-bin目录下。
问题解决。