Home > Software design >  Bad Request when setting CURLOPT_POSTFIELDS in PHP cURL
Bad Request when setting CURLOPT_POSTFIELDS in PHP cURL

Time:07-15

PHP VERSION: 8.1

I am getting a 400 Bad Request error when using Cloudflare Stream via PHP cURL, but only if CURLOPT_POSTFIELDS is set.

My code:

$tokench = curl_init();
curl_setopt($tokench, CURLOPT_URL, "https://api.cloudflare.com/client/v4/accounts/".getenv("CLOUDFLARE_ACCOUNT")."/stream/".urlencode($_GET["video"])."/token");
 curl_setopt($tokench, CURLOPT_POST, 1);
 curl_setopt($tokench, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($tokench, CURLOPT_HTTPHEADER, ["Authorization: Bearer ".getenv("CLOUDFLARE_TOKEN"), "Content-Type: application/json"]);
 curl_setopt($tokench, CURLOPT_POSTFIELDS, "downloadable=true");
 $tokenraw = curl_exec($tokench);
 curl_close($tokench);
 $tokenarr = json_decode($tokenraw, true);

$tokenarr["success"] is false.

CodePudding user response:

I fixed it on my own. I had to JSON encode the POSTFIELDS because the Content Type was application/json. CODE EXAMPLE:

$tokench = curl_init();
curl_setopt($tokench, CURLOPT_URL, "https://api.cloudflare.com/client/v4/accounts/".getenv("CLOUDFLARE_ACCOUNT")."/stream/".urlencode($_GET["video"])."/token");
curl_setopt($tokench, CURLOPT_POST, 1);
curl_setopt($tokench, CURLOPT_RETURNTRANSFER, true);
curl_setopt($tokench, CURLOPT_HTTPHEADER, ["Authorization: Bearer ".getenv("CLOUDFLARE_TOKEN"), "Content-Type: application/json"]);
curl_setopt($tokench, CURLOPT_POSTFIELDS, json_encode(["downloadable" => true]));
$tokenraw = curl_exec($tokench);
curl_close($tokench);
$tokenarr = json_decode($tokenraw, true);

$tokenarr["success"] is true!

  • Related