Php Curl HTTP POST REQUEST使用嵌套键值对设置自定义标头

时间:2016-09-02 09:51:25

标签: php xml curl http-post

如何使用Curl在php中设置此标头? (CustomInfo元素是数组(嵌套键值对),AuthenticationInfo元素是数组(嵌套键值对))

<xml bla bla...>
    <Header>
    <CustomInfo>
    <IsTestMessage>true</IsTestMessage>
    <IsContentCompressed>false</IsContentCompressed>
    </CustomInfo>
    <AuthenticationInfo>
    <ApplicationId>SomeId</ApplicationId>
    <VersionId>0.9</VersionId>
    <RelationId></RelationId>
    <UserId>SomeUserId</UserId>
    <Password>SomePassword</Password>
    </AuthenticationInfo>
    </Header>
    <Body>
    <!--etc...(actual xml)-->
    </Body>
    </xml bla bla...>

通常我会这样做:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/process.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = array();
$headers[] = 'key: value';
$headers[] = 'key2: value2';//and so on...

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);

print  $server_output ;

但是当标题包含嵌套的键值对时,如何完成?

编辑1:

以这种方式完成但不起作用(真正的新手,所以我一定做错了):

$headers = array();
            $headers[] = array('CustomInfo' => array(
                                'IsTestMessage' => "true",
                                'IsContentCompressed' => "false")
                                );
            $headers[] = array('AuthenticationInfo' => array(
                'ApplicationId' => "SomeId",
                'VersionId' => "0.9",
                'RelationId' => "",
                'UserId' => "SomeUserId",
                'Password' => "SomePassword"
                )
                );
            $headers = serialize($headers);

            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));

警告:curl_setopt():您必须使用CURLOPT_HTTPHEADER参数传递对象或数组

编辑2:

当我没有序列化$ header时,我得到:

注意:数组转换为字符串

1 个答案:

答案 0 :(得分:0)

理想情况下,应该使用CURLOPT_POSTFIELDS,除非这是外部API的特定要求

$myArray = array();
$myArray[] = array('key' => 'value');
$myArray[] = array('key2' => array('value2' => array('foo' => 'bar')));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,array('myVars' => $vars, 'myArray' => $myArray));  //Body

然后访问$_POST['myArray']

  

警告:可以注入标题和POST变量,因此我还建议您对发件人进行检查(例如$_SERVER['REMOTE_ADDR'] == 127.0.0.1),如果这些请求仅来自您的自己的服务器

我不提及访问$_POST而未提及:How can I prevent SQL injection in PHP?