1、学习用c/c++写cgi程序

    CGI全称Common Gateway Interface(共同编程接口),是一种编程接口,不论什么语言,只要按照该接口的标准编写出来的程序,即可叫做CGI程序。CGI 程序的输入/输出是使用编程语言的标准输入/标准输出,所以用C/C++来写 CGI 程序就好象写普通程序一样。

1)CGI 程序的通信方式

    当有数据从浏览器传到 Web 服务器后,该服务器会根据传送的类型(基本有二类:GET/POST),将这些接收到的数据传入QUERY_STRING或变量中CGI程序可以通过标准输入,在程序中接收这些数据。当要向浏览器发送信息时,只要Web服务器发送特定的文件头信息,即可通过标准输出将信息发往Web服务器Web服务器处理完这些由CGI程序发来的信息后就会将这些信息发送给浏览器。这样就是CGI程序的通信方式了。

2)接收数据

    GET方式接收到的数据保存在Web服务器的QUERY_STRING变量里,而通过POST方式接收到的数据是保存在这个Web服务器变量里。它们的唯一区别就是:以GET方式接收的数据是有长度限制;而用POST方式接收的数据是没有长度限制的。并且,以GET方式发送数据,可以通过URL的形式来发送,但POST方式发送的数据必须要通过Form才到发送。

将程序用gcc编译,结果放在放在/cgi/bin目录下,在brower中输入

程序示例

helloword.c
#include <stdio.h>
main()
{
printf(
"Content-type:text/html\n\n"); //文件显示类型
printf("Hello,World!"); //显示内容
}

http://localhost/cgi-bin/helloworld

则可输出hello,world

see more in 【1

3、使用cgi处理get和post的数据请求简单示例

说明:apache+suse10.1

cgi程序

View Code
#include <stdio.h>
#include
<stdlib.h>

#define MAXLEN 80

int main(void)
{
long len;
char *lenstr, poststr[80];
printf(
"Content-Type:text/html\n\n");

char *pRequestMethod;
setvbuf(stdin, NULL, _IONBF,
0); /*turn off stdin's cache*/

pRequestMethod
= getenv("REQUEST_METHOD");

if (strcmp(pRequestMethod, "POST") == 0)
{
printf(
"<TITLE>This is Post operation</TITLE>\n");
lenstr
= getenv("CONTENT_LENGTH");
//if(lenstr == NULL || len > MAXLEN)
if(lenstr == NULL)
{
printf(
"<P>Post form error");
}
else
{
len
= atoi(lenstr);
fgets(poststr, len
+ 1, stdin);
printf(
"%s",poststr);
}
}
if (strcmp(pRequestMethod, "GET") == 0)
{
printf(
"<TITLE>This is Get operation</TITLE>\n");
char *qa;
printf(
"<TITLE>The reault of Get is:\n</TITLE>\n");
qa
= getenv("QUERY_STRING");
printf(
"%s",qa);
}
return 0;
}

html程序

<html>
<body>
<h1>It works!</h1>
<h2>I am here!</h2>

<FORM ACTION="./cgi-bin/getpost" METHOD="get">
<INPUT TYPE="text" NAME="Text" VALUE="This is get operation">
<INPUT TYPE="submit" VALUE="Get"></INPUT>
</FORM>
<BR> 

<FORM ACTION="./cgi-bin/getpost" METHOD="post">
<INPUT TYPE="text" NAME="Text" VALUE="This is post operation">
<INPUT TYPE="submit" VALUE="Post"></INPUT>
</FORM>
<BR>

</body>
</html>

1http://lzquan.iteye.com/blog/286551

1 http://blog.csdn.net/lanmanck/article/details/5359403

2 http://gaodi2002.blog.163.com/blog/static/232076820106352058738/

原文地址:https://www.cnblogs.com/mydomain/p/2147734.html