简体   繁体   中英

Equivalent php options for curl

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

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

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'
        )
    ))
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM