将curl转换为PHP

时间:2016-06-09 08:29:17

标签: php curl

我在下面尝试使用终端正常运行并返回字符串确定或失败。

curl -k -X POST -H 'Content-Type: application/json' -d '{"username":"username","password":"password"}' https://123.123.123.123:1234/session

当我尝试转换它不起作用时。

    <?php
$data = array( "username" => "username", "password" => "password" );

$data_string = json_encode($data);

$ch = curl_init( "https://123.123.123.123:1234/apicall" ); curl_setopt_array( $ch, array( CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ), CURLOPT_POSTFIELDS => $data_string, CURLOPT_RETURNTRANSFER => true ));

$result = curl_exec( $ch ); //Make it all happen and store response

?>

1 个答案:

答案 0 :(得分:0)

curlopt_postfields接受一个数组,因此您不需要json_encode数据数组:

CURLOPT_POSTFIELDS => $data

查看有关curlopt选项的更多信息:

  

此参数可以作为urlencoded字符串传递   &#39; PARA1 = VAL1&安培; PARA2 = val2的&安培; ...&#39;或者作为字段名称为键的数组   和现场数据作为价值。

您的示例中也有一个太多的结束括号,而您没有关闭连接。完整代码:

<?php
$data = array("username" => "username", "password" => "password");

$ch = curl_init("https://123.123.123.123:1234/apicall");
curl_setopt_array(
    $ch,
    array(
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ),
        CURLOPT_POSTFIELDS => $data_string,
        CURLOPT_RETURNTRANSFER => true
    )
);

$result = curl_exec($ch);

curl_close($ch);