如何在cURL php中发布JSON数据和请求令牌(在标题中)

时间:2017-11-11 05:56:04

标签: php azure curl

我想将登录凭据和密码作为JSON数据发送,并将请求令牌作为我的http标头发送。

最初是这样的,

{
    "Username":"admin",
    "Password":"root123",
   "PinCode” : "hello321"
}

我也需要发布请求标头令牌

如果请求没问题,我应该得到如下的JSON响应,

{
            "Title": "Mr.",
            "Name": "Pushkov",
            "Age": "18"

} 

我正在尝试在cURL PHP中执行此操作。下面是我的控制器代码。

我尝试将请求令牌保存到变量并将其传递到标头中,并将用户名,密码和PIN码作为JSON数据发布。如果应显示登录成功而不是用户信息。但是我很难从这里开始。我怎样才能做到这一点?

public function send_data() {

$url='http://samplesite.azurewebsites.net/api/member/loginmember';

$ch = curl_init('http://localhost/main');


$data = array("Username" =>$this->input->post('un'), "Password"  =>$this->input->post('pw'), "PinCode" =>$this->input->post('PinCode'));                                                                    
$data_string = json_encode($data);   


//echo $data_string; 

// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
); 
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);


//var_dump(json_decode($result, true));
$data2=json_decode($result, true);
$ref_id = ( ( is_array( $data2["UserCode"] ) ? implode(", ", $data2["PinCode"]) : $data2["RequestToken"] ) ); // array to string
$acc_t = $data2["RequestToken"];
$uun = $data2["UserCode"];

//echo $acc_t;


// Closing
curl_close($ch);
//print  $result ;
}

1 个答案:

答案 0 :(得分:0)

在上面的代码中,您将网址设置为curl_init(),并且您还在CURLOPT_URL选项中传递了另一个网址。您不能在一个cURL请求中执行此操作。

如果您使用的是OAuth 2.0,则可以将访问令牌设置为CURLOPT_XOAUTH2_BEARER选项。

更多信息,请参阅PHP manual on cURL Functions