_winds 发表于 2017-1-13 11:27:39

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”.
  额,这个有点恶心,如果有哪位大牛知道为什么,欢迎回帖说明原因。
  

  

----------------------------------------分割线------------------------------
接下来准备去做LCD、IGBT、HMI方面的电商
页: [1]
查看完整版本: Apache下c语言的cgi如何获得Get,Post参数