如何用C++ CGI程序获取GET/POST变量?

chy5wohz  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(177)

我的google-fu失败了,我正在寻找一个基本的方法来从我的服务器上的html论坛页面获得GET/POST数据,以便在一个只使用基本库的c++ CGI程序中使用。
(使用Apache服务器,在ubuntu 22.04.1上)
这是我试过的代码
HTML页面:

<!doctype html>
    <html>
    <head>
    <title>Our Funky HTML Page</title>
    </head>
    <body>
    Content goes here yay.
    <h2>Sign Up </h2>
        <form action="cgi-bin/a.cgi" method="post">  
            <input type="text" name="username" value="SampleName">
            <input type="password" name="Password" value="SampleName"> 
    
            <button type="submit" name="Submit">Text</button>
        </form>
    </body>
    </html>

这是我试过的c++代码:

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

    int main()
    {
        printf("Content-type:text/plain\n\n");
        printf("hello World2\n");
    
         // attempt to retrieve value of environment variable
         char *value = getenv( "username" ); // Trying to get the username field
         if ( value != 0 ) {
            printf(value);
         } else {
            printf("Environment variable does not exist."); // if it failed I get this message
         }
         printf("\ncomplete\n");
    
    return 0;
    }

我感觉“getenv”在这里不适合使用......但它适用于“SERVER_NAME”之类的东西。
有什么想法吗?

s3fp2yjn

s3fp2yjn1#

好的,有两种不同的方法,取决于是post还是get方法:

  • 获取- html:
<!doctype html>
 <html>
 <head>
 <title>Website title obv</title>
 </head>
 <body>
 Content goes here yay.
 <h2>Sign Up </h2>
 <form action="cgi-bin/a.cgi" method="get">  
    <input type="text" name="username" value="SampleName">
    <input type="password" name="Password" value="SampleName"> 
 
    <button type="submit" name="Submit">Text</button>
 </form>
 </body>
 </html>

和c++(脚本?)读取get值:

#include <stdio.h>
#include <iostream>

int main()
{
     printf("Content-type:text/plain\n\n");
     
     char *value = getenv( "QUERY_STRING" );  // this line gets the data
     if ( value != 0 ) {
        printf(value);
     } else {
        printf("Environment variable does not exist.");
     }
     return 0;
}

您必须手动解析数据

  • 开机自检-
    html:只需将“get”更改为“post”
    C++ :
#include <stdio.h>
#include <iostream>
#include <string>
#include <stdlib.h>

int main()
{
    printf("Content-type:text/plain\n\n");

    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
    
return 0;
}

同样,您必须手动解析数据,但现在您可以自己处理这些值。
玩得开心点!

相关问题