简体   繁体   中英

cURL PHP Headers and Data

I am attempting to recreate a cURL request that looks like this:

curl -X "POST" "https://urlhere.com" \
  -H "authorization: TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d $'{
   "subscriptionid": "",
   "templateid": "",
   "to": [
      ""
   ],
   "subject": "",
   "data": {
      "foo": 123,
      "bar": 123
   }
}'

Can anyone help me figure out how to create this in PHP? I currently have:

curl_setopt($cURL,CURLOPT_URL, $url);
curl_setopt($cURL,CURLOPT_POST, 1);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array('authorization: '. $token));
curl_setopt($cURL, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($cURL, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($cURL,CURLOPT_POSTFIELDS, $json);
curl_setopt($cURL, CURLINFO_HEADER_OUT, true);

And of course my init, exec, and close statements.

But I receive back an error 401. Unauthorized.

According to your given curl this is the code which i generated from postman

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://urlhere.com/",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\n   \"subscriptionid\": \"\",\n   \"templateid\": \"\",\n   \"to\": [\n      \"\"\n   ],\n   \"subject\": \"\",\n   \"data\": {\n      \"foo\": 123,\n      \"bar\": 123\n   }\n}",
  CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "authorization: TOKEN",
    "cache-control: no-cache",
    "content-type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

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