[英]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.