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

时间:2015-10-10 09:00:12

标签: php c++ shell

我想将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

的回复应该相同

2 个答案:

答案 0 :(得分:1)

您需要创建一个管道才能将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;

答案 1 :(得分:1)

谢谢@yacc,我找到了一种方法,这是我用的方式演示 http://cpp.sh/4wgu

我们的想法是:我们将分叉当前进程,使用2个管道:1表示stdin,1表示stdout。在父进程中,我们将使用一个管道将字符串写入子进程的stdin,在子进程中,我们将为子进程的stdout输出一个管道。通过这种方式,我们可以写入stdin并从父进程读取子进程的stdout