[英]how to get a GET/POST variable with a c++ CGI program?
我的 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”之类的东西。
有什么想法吗?
好的,有 2 种不同的方法,具体取决于它是 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++(脚本?)读取获取值:
#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:只需将“获取”更改为“发布”
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;
}
同样,您必须手动解析数据,但现在您可以自己使用这些值。
玩得开心!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.