gpt4 book ai didi

php - 使用 REQUEST_METHOD ="POST"从 C++ 调用 php-cgi

转载 作者:行者123 更新时间:2023-11-30 03:48:42 25 4
gpt4 key购买 nike

我想将 shell 脚本转换为 C++。请帮助我。

这是我的 shell 脚本文件。它运行良好,但是当我转向 C++ 时,它无法正常工作

test.sh

#!/bin/sh
REQUEST_DATA="var_1=val_1&var_2=val_2"
export GATEWAY_INTERFACE="CGI/1.1"
export SERVER_PROTOCOL="HTTP/1.1"
export QUERY_STRING="test=querystring"
export REDIRECT_STATUS="200"
export SCRIPT_FILENAME="/test.php"
export REQUEST_METHOD="POST"
export CONTENT_LENGTH=${#REQUEST_DATA}
export CONTENT_TYPE="application/x-www-form-urlencoded;charset=utf-8"
echo $REQUEST_DATA | /usr/bin/php-cgi

test.php

<?php
print_r($_POST);
?>

当我运行 sh test.sh 时,我得到了响应:

X-Powered-By: PHP/5.6.13
Set-Cookie: PHPSESSID=f4ntbasno365p08tf94drl7026; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-type: text/html; charset=UTF-8

Array
(
[var_1] => val_1
[var_2] => val_2
)

当我尝试将其转换为 C++ 时

char **sysCline = NULL;
char **sysEnv = NULL;
std::string sData = "var_1=val_1&var_2=val_2";

std::vector<std::string> aArgs;
aArgs.push_back("/usr/bin/php-cgi");
aArgs.push_back("/test.php");
sysCline = new char*[aArgs.size() + 1];
for (i=0; i<aArgs.size(); i++) {
sysCline[i] = new char[aArgs[i].size()+1];
::strncpy(sysCline[i], aArgs[i].c_str(), aArgs[i].size()+1);
}
sysCline[aArgs.size()] = NULL;

// Construct environment
std::vector<std::string> aEnv;
aEnv.push_back("GATEWAY_INTERFACE=CGI/1.1");
aEnv.push_back("SERVER_PROTOCOL=HTTP/1.1");
aEnv.push_back("QUERY_STRING=test=querystring");
aEnv.push_back("REDIRECT_STATUS=200");
aEnv.push_back("REQUEST_METHOD=POST");
aEnv.push_back("CONTENT_TYPE=application/x-www-form-urlencoded;charset=utf-8");
aEnv.push_back("SCRIPT_FILENAME=/test.php");
aEnv.push_back("CONTENT_LENGTH="+ to_string(sData.length()) );
sysEnv = new char*[aEnv.size() + 1];
for (i=0; i<aEnv.size(); i++) {
sysEnv[i] = new char[aEnv[i].size()+1];
::strncpy(sysEnv[i], aEnv[i].c_str(), aEnv[i].size() + 1);
}
sysEnv[aEnv.size()] = NULL;

execve(sysCline[0], sysCline, sysEnv);

运行时,我得到响应:

X-Powered-By: PHP/5.6.13
Set-Cookie: PHPSESSID=2vdp947ghlg0h8st66c9ll3vt6; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-type: text/html; charset=UTF-8

Array
(
)

它应该与 sh test.sh 相同的响应

最佳答案

您需要创建一个管道以便将 POST 数据传递给脚本:

char *echocmd[] = {"echo", "var_1=val_1&var_2=val_2", NULL};
int pp[2];
int pid, res;

pipe(pp);

if ((pid = fork()) != 0)
{
dup2(pp[1], 1);
close(pp[0]);

res = execvp(echocmd[0], echocmd);
}
else
{
dup2(pp[0], 0);
close(pp[1]);

res = execve(sysCline[0], sysCline, sysEnv);
}

close(pp[1]);
return res;

关于php - 使用 REQUEST_METHOD ="POST"从 C++ 调用 php-cgi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33052169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com