W3docs

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:

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:

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

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

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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:

Example of using curl_setopt_array() function to set multiple options at once in PHP

<?php

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

$ch = curl_init();

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

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

This alternative approach reduces the number of curl_setopt calls by passing an associative array of options to curl_setopt_array().