Reputation: 1397
I am trying to send a curl request with the following options, but I do not know how to send the data with the -d option in the php curl setup.
curl -X 'POST' \
-H 'Content-Type: application/json; charset=utf-8' \
-H 'Authorization: Bearer x'
-v 'URL' \
-d
'{
"input": {
"urn": "num",
"compressedUrn": true,
"rootFilename": "A5.iam"
}
}'
In other words, I know how to send the header using ...
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer x'
));
But I do not know the equivalent for the -d flag.
Thanks
Upvotes: 1
Views: 1266
Reputation: 21503
But I do not know the equivalent for the -d flag.
it's CURLOPT_POSTFIELDS.
curl_setopt_array($ch, array(
CURLOPT_URL => 'URL',
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer x',
'Content-Type: application/json; charset=utf-8'
),
CURLOPT_POSTFIELDS => json_encode(array(
'input' => array(
'urn' => 'num',
'compressedUrn' => true,
'rootFilename' => 'A5.iam'
)
))
));
Upvotes: 1
Reputation: 1600
Its the data that needs to be sent with the request
I normally wrap this into a function to make handling errors / success easier. Especially if you are dealing with an API like paypal or something
// create the object (you can do this via a string if you want just remove the json encode from the postfields )
$request = new stdClass(); //create a new object
$request->input = new stdClass(); // create input object
$request->input->urn = 'num'; // assign values
$request->input->compressedUrn = true;
$request->input->rootFilename = 'A5.iam';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'URL HERE');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $request ) ); // encode the object to be sent
curl_setopt($ch, CURLOPT_POST, true); // set post to true
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [ //set headers
'Content-Type: application/json',
'Authorization: Bearer x'
]);
$result = curl_exec ($ch);
if ( ! $result) { //check if the cURL was successful.
// do something else if cURL fails
}
curl_close ($ch);
$return = json_decode( $result ); // object if expecting json return
Upvotes: 1