Apache下c语言的cgi如何获得Get,Post参数

Apache下的c语音的cgi如何获得Get,Post参数

 

作为实验,自己在ubuntu上搭建apache服务器,提供了网络服务(这一步比较简单,后续补充上来)。遇到的一个问题是,如何获得页面提交的Get或者Post函数。下面会给出具体的源码来实现这一个目的。

 

先看整体效果图


这样来提交到apache上的test.cgi,应该可以正常显示”hello world”

 

1.      先看该html的页面的源码,标红色的为两个button

 

<html>                                                                         

    <head>

        <title>This isMichael</title>

    </head>

    <body>

        <formaction="/cgi-bin/test.cgi" method="get">

               <input type="text" name="text" value='helloworld'/>

               <input type="submit" value="Get" method=get />

        </form>

 

        <formaction="/cgi-bin/test.cgi" method="post">

               <input type="text" name="text" value="helloworld"/>

               <input type="submit" value="Post" method=post/>

        </form>

   </body>

</html>

2.      C编写的test.cgi 如下,标红色的地方为核心,表示如何调用系统函数获得对应的环境变量:

include<stdio.h>

#include<stdlib.h>

#include<unistd.h>

#include<time.h>

#include<iostream>

 

usingnamespace std;

 

 

intmain()

{

        printf("Content-type:text/html\n\n");

 

        /* Parameter by Get Method */

        char *param =getenv("QUERY_STRING");

        while( param != NULL && *param!= '\0' )

        {

                printf("%c", *param);

                param++;

        }                                                                                                                             

        /* Parameter by Post Method */

        int n=0;

       if(getenv("CONTENT_LENGTH") )

               n=atoi(getenv("CONTENT_LENGTH") );

        printf("thecontent length is %d", n );

        for (int i=0;i<n;i++)

                putchar(getchar());

        putchar('\n');

        fflush(stdout);

 

        return 0;

}

                                                         

 

经过我的测试,上面的代码是可以运行的。但是有个小细节要注意一下

“hello world” 在作为参数传递时会变成 “hello+world”.

额,这个有点恶心,如果有哪位大牛知道为什么,欢迎回帖说明原因。




  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值