I need to send a POST request to Cloudflare API, Their API example is:
curl -X POST "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/purge_cache" \
-H "X-Auth-Email: [email protected]" \
-H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}
I have been trying from my functions.php file to make a POST request. Here is my code:
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, 'my_url' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array(
'X-Auth-Email' => 'my_email',
'X-Auth-Key' => 'cf_api_key',
'Content-Type' => 'application/json',
));
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode( '{"purge_everything":true}' ));
$result = curl_exec($curl);
curl_close($curl);
var_dump($result);
I am getting this response
'''{"success":false,"errors":[{"code":9106,"message":"Missing X-Auth-Key, X-Auth-Email or Authorization headers"}]} bool(true) '''
Where and how should I put my X-Auth-Key etc?
CodePudding user response:
you have to use the array of httpheader as single values, separeted with doublepoint, not as key value pair:
please see this example:
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, 'my_url' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array(
'X-Auth-Email: my_email',
'X-Auth-Key: cf_api_key',
'Content-Type: application/json',
));
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, ["purge_everything"=>true] );
$result = curl_exec($curl);
curl_close($curl);
var_dump($result);