How to include Authorization header in cURL POST HTTP Request in PHP?

To include the Authorization header in a cURL POST request in PHP, you can use the CURLOPT_HTTPHEADER option and pass it an array of headers like this:

<?php

$headers = ['Authorization: Bearer YOUR_ACCESS_TOKEN', 'Content-Type: application/x-www-form-urlencoded'];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://example.com/api/endpoint");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "key=value");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
curl_close($ch);

Watch a course Learn object oriented PHP

This will send a POST request to https://example.com/api/endpoint with the Authorization header set to Bearer YOUR_ACCESS_TOKEN and the Content-Type header set to application/x-www-form-urlencoded.

You can also use the curl_setopt_array function to set multiple options at once:

<?php

$headers = ['Authorization: Bearer YOUR_ACCESS_TOKEN', 'Content-Type: application/x-www-form-urlencoded'];