Post the data with header in curl not working in php?

独自空忆成欢 提交于 2019-12-11 18:29:41

问题


I'm trying to create the box app users using PHP. The curl for create user as follows, and it is working on terminal

curl https://api.box.com/2.0/users \
-H "Authorization: Bearer <Access token>" \
-d '{"name": "New User", "is_platform_access_only": true}' \
-X POST

Same thing I have tried with php But it is giving the following error

{"type":"error","status":400,"code":"invalid_request_parameters","help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Invalid input parameters in request","request_id":"6688622675982fb5339a37"}

The following one I have tried

$developer_token = "TOKEN" ;
$access_token_url = "https://api.box.com/2.0/users";

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);

//Adding Parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'name'=>'NEW USER', 
    'is_platform_access_only'=>'true',
     ));

//Adding Header 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Bearer '.$developer_token
     ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response1 = curl_exec($ch);

If I remove the Post parameters, and run with only headers it is give the result of users. But with post it is throws error.


回答1:


I have rise the same question in Perl tag with Perl code. There I got answer by user @melpomene.

We should encode the data as JSON. It is working, Then the final code is

$data = array(name=>SOMENAME,is_platform_access_only=>true);
$data = json_encode($data);
$header = array("Authorization: Bearer <TOKEN>");
$ch = curl_init("https://api.box.com/2.0/users/");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
curl_close($ch);


来源:https://stackoverflow.com/questions/45481851/post-the-data-with-header-in-curl-not-working-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!