In today’s interconnected world, developers often rely on APIs to access and share data between different platforms. A cURL is a popular tool for making HTTP requests, and it’s widely supported in PHP. To protect the integrity of API data, you will include authorization headers in your cURL requests.
In this article, we will walk you through how to add authorization headers to cURL requests in PHP using code examples for various authentication mechanisms, such as API keys, Bearer tokens (OAuth), and Basic authentication. Additionally, we will cover error handling and best practices for securing sensitive data.
Authorization Headers Code Example
<?php
// Define the API key, access token, username, and password
$apiKey = "your_api_key_here";
$accessToken = "your_access_token_here";
$username = "your_username_here";
$password = "your_password_here";
// Initialize a cURL session
$ch = curl_init("https://api.example.com/data");
// Set the API key header
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Apikey $apiKey"));
// Set the Bearer token header
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $accessToken"));
// Set the username and password for Basic authentication
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
// Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the cURL request
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Print the response
echo $response;
?>
Steps to Adding Authorization Headers
The following steps are required for adding authorization headers to the cURL requests in PHP.
- Initialize a cURL session: Use the curl_init() function to create a new cURL session.
- Set the API URL: Use the CURLOPT_URL option with the curl_setopt() function to specify the URL of the API endpoint you want to request.
- Choose the authorization method: Depending on the API’s authentication mechanism, decide whether to use an API key, Bearer token (OAuth), or Basic authentication (username and password).
- API Key: If the API requires an API key, define it as a variable, and set the CURLOPT_HTTPHEADER option with the API key.
- Bearer Token (OAuth): If the API uses OAuth, obtain an access token, define it as a variable, and set the CURLOPT_HTTPHEADER option with the Bearer token.
- Basic Authentication: If the API requires Basic authentication, define the username and password as variables, and set the CURLOPT_USERPWD option with the username and password.
Article Highlights
- cURL is a widely used command-line tool and library for transferring data using various protocols, including HTTP, HTTPS, and FTP. PHP commonly uses it to make API requests and retrieve data from external sources.
- Adding authorization headers to cURL requests is crucial for securing your web application and ensuring only authorized users can access protected resources.
- Different types of authorization headers require different types of credentials, such as a username and password or a token.
- To add authorization headers to cURL requests using PHP, you must use the curl_setopt() function to set the CURLOPT_HTTPHEADER option.
- Authorization headers are essential in API requests as they authenticate the request and ensure secure access to sensitive data.
- Code examples for adding different authorization headers to cURL requests in PHP, including API keys, Bearer tokens (OAuth), and Basic authentication (username and password).
- To handle errors, we can use cURL error codes and error messages and the CURLOPT_RETURNTRANSFER and CURLOPT_FAILONERROR options to check for errors during the request.
- Best practices for using cURL in PHP include safeguarding sensitive data by using environment variables for credentials, handling rate limits and API restrictions, and properly closing and releasing cURL resources to prevent memory leaks and ensure efficient resource usage.

Table of Contents
In this article, we will cover the following topics.
- An Overview of cURL and its use in PHP.
- The Importance of authorization headers in API requests.
- Setting up the PHP environment.
- Adding authorization headers to cURL requests.
- Error handling and troubleshooting.
- Best practices.
- How to Add Authorization Headers to cURL Requests Summary?
An Overview of cURL and its use in PHP
cURL (Client URL) is a powerful command-line tool and library that allows developers to transfer data via various network protocols, including HTTP, HTTPS, FTP, and more. In PHP, the cURL library is widely used to make HTTP requests and interact with APIs. The PHP cURL extension enables developers to harness cURL’s capabilities within their PHP scripts, providing a flexible and efficient way to access and exchange data with other web services.
Check out our articles on What is cURL Used For | 2023 PHP Code Examples & Alternatives
The Importance of authorization headers in API requests
Authorization headers are a crucial component of API requests as they provide access control and ensure the security and integrity of data being exchanged between clients and APIs. These headers typically contain authentication credentials, such as API keys or access tokens, which the API provider requires to verify the requester’s identity and determine whether they can access the requested resources.
There are several reasons why authorization headers are important in API requests:
Security.
API providers can ensure that only authorized clients can access their resources by including authorization headers in API requests. This prevents unauthorized access, data breaches, and potential API abuse.
Access Control.
Authorization headers allow API providers to manage and control access to their resources per-client or per-user basis. By verifying the credentials in the header, the API provider can grant or deny access to specific resources based on the client’s permissions.
Rate Limiting and Usage Monitoring.
Using authorization headers, API providers can track the usage of their API by individual clients or users. This enables them to enforce rate limits, monitor usage patterns, and potentially detect any abnormal or malicious activity.
Auditing and Logging.
Including authorization headers in API requests allows API providers to maintain a comprehensive audit trail of who accessed which resources and when. This can be useful for troubleshooting, security analysis, and compliance with data protection regulations.
Using authorization headers in API requests is essential for maintaining security, access control, and monitoring API usage while providing valuable insights for auditing and logging purposes. By including authorization headers in your API requests, you can ensure that your applications and services adhere to best practices and provide a secure and controlled environment for data exchange.
Setting up the PHP Environment
Authorization headers to our cURL requests using PHP, we need to ensure that our PHP environment is set up correctly. Here are the steps to do that:
Ensure PHP and cURL extensions are installed
Before you implement the examples in the tutorial, you must ensure that your system has installed PHP and the cURL extension. PHP is a server-side scripting language that allows you to create dynamic web pages and interact with APIs, while the cURL extension provides a way to use cURL within your PHP scripts.
To check if PHP is installed, you can use the following command in your terminal or command prompt:
php -v
This command will display the installed PHP version if it is present on your system.
Next, we need to ensure that the cURL extension is installed and enabled in PHP. The cURL extension is required for making HTTP requests with cURL.
We can check if the cURL extension is installed by running the following command:
php -m | grep curl
If the cURL extension is installed, this command will output “curl.” If the cURL extension is not installed, you must install it using your system’s package manager or downloading it from the official cURL website.
Create a new PHP file for the examples.
Once you have confirmed that PHP and the cURL extension are installed, create a new PHP file where you will implement the authorization header examples provided in this tutorial. This file will be your testing environment for adding authorization headers to cURL requests using PHP.
To create a new PHP file, open your preferred code editor or IDE, create a new file, and save it with a .php extension (e.g., auth_headers_example.php).
Now, you can add the provided code examples to this file, modify them according to your specific use case, and test them in your PHP environment. By setting up your PHP environment and creating a new PHP file, you are ready to follow the tutorial and implement the examples for adding authorization headers to cURL requests using PHP.
Adding authorization headers to cURL requests
Basic cURL request structure in PHP
The basic structure of a cURL request in PHP involves:
- Initializing a cURL session.
- Setting the necessary options.
- Executing the request.
- Closing the session.
Here’s a simple example:
// Initialize a cURL session
$ch = curl_init();
// Set the URL of the API endpoint
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");
// Other options, such as CURLOPT_RETURNTRANSFER, can be set here
// Execute the cURL request
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
Types of authorization headers
There are several types of authorization headers that can be added to cURL requests in PHP, depending on the API’s authentication mechanism.
The most common types are:
- API keys: a unique identifier used to authenticate with an API
- Bearer tokens (OAuth): an access token used to authenticate with a server or API
- Basic authentication (username and password): a username and password used to authenticate with a server
API keys.
An API key is a unique identifier assigned to each client or user to authenticate the client when making API requests.
To add an API key to the cURL request, set the CURLOPT_HTTPHEADER option with the key.
$apiKey = "your_api_key_here";
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Apikey $apiKey"));
Bearer tokens (OAuth).
OAuth (Open Authorization) is an authorization protocol that allows third-party applications to access resources on behalf of a user without exposing their credentials. This mechanism uses access tokens to authenticate the client when making API requests.
To add a Bearer token to the cURL request set the CURLOPT_HTTPHEADER option with the token.
$accessToken = "your_access_token_here";
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $accessToken"));
Basic authentication (username and password).
Basic authentication is an authentication method that requires the client to provide a username and password when making API requests. These credentials are usually encoded using base64 and included in the authorization header.
To add Basic authentication to the cURL request set the CURLOPT_USERPWD option with the username and password.
$username = "your_username_here";
$password = "your_password_here";
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
By understanding the basic cURL request structure in PHP and the different types of authorization headers, you can securely authenticate your API requests and access the resources provided by the API.
Remember to use the appropriate authorization header based on the API’s authentication mechanism and follow the API provider’s guidelines for managing and storing sensitive data like API keys, access tokens, and credentials.
Code examples for each authorization header type
Here are some code examples for adding each type of authorization header to a cURL request using PHP:
API key.
To add an API key as an authorization header, we can define the API key as a variable and include it in the CURLOPT_HTTPHEADER option.
Here are the steps:
1. Define API key as a variable.
// Define the API key as a variable
$apiKey = "your_api_key_here";
2. Set CURLOPT_HTTPHEADER with the API key.
// Set the API key as a header
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Apikey $apiKey"));
3. Execute the cURL request.
// Execute the request and retrieve the response
// Initialize a cURL session
$ch = curl_init("https://api.example.com/data");
// Set the API key header
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Apikey $apiKey"));
// Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the cURL request
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
Bearer token (OAuth).
We first need to obtain the access token to add a Bearer token as an authorization header. Once we have the access token, we can define it as a variable and include it in the CURLOPT_HTTPHEADER option.
Here are the steps:
1. Obtain the access token.
Depending on the API provider and their OAuth implementation, follow their specific instructions to obtain an access token.
2. Define the access token as a variable.
// Obtain the access token
$accessToken = "your_access_token_here";
3. Set CURLOPT_HTTPHEADER with the Bearer token.
// Set the Bearer token as a header
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $accessToken"));
4. Execute the cURL request.
// Execute the request and retrieve the response
// Initialize a cURL session
$ch = curl_init("https://api.example.com/data");
// Set the Bearer token header
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $accessToken"));
// Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the cURL request
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
Basic authentication (username and password).
To add Basic authentication as an authorization header, we can define the username and password as variables and include them in the CURLOPT_USERPWD option.
Here are the steps:
1.Define the username and password as variables.
// Define the username and password as variables
$username = "your_username_here";
$password = "your_password_here";
2. Set CURLOPT_USERPWD with the username and password.
// Set the username and password as a header
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
3. Execute the cURL request.
// Execute the request and retrieve the response
// Initialize a cURL session
$ch = curl_init("https://api.example.com/data");
// Set the username and password for Basic authentication
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
// Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the cURL
$response = curl_exec($ch);
curl_close($ch);
By following these code examples for each authorization header type, you can securely authenticate your API requests using API keys, Bearer tokens (OAuth), or Basic authentication (username and password).
Make sure to adjust the code according to your specific API requirements and use the appropriate method for the API you are working with.
Complete PHP Code Example
Here is a complete code example that demonstrates how to add an API key, Bearer token (OAuth), and Basic authentication (username and password) authorization headers to cURL requests in PHP:
<?php
// Define the API key, access token, username, and password
$apiKey = "your_api_key_here";
$accessToken = "your_access_token_here";
$username = "your_username_here";
$password = "your_password_here";
// Initialize a cURL session
$ch = curl_init("https://api.example.com/data");
// Set the API key header
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Apikey $apiKey"));
// Set the Bearer token header
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $accessToken"));
// Set the username and password for Basic authentication
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
// Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the cURL request
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Print the response
echo $response;
?>
The above code example can be adapted for different APIs by adjusting the API endpoint URL and the required authorization header type.
Note that in this example, we’ve included all three types of authorization headers (API key, Bearer token, and Basic authentication) for illustrative purposes. In practice, you would only need to include one type of authorization header depending on the authentication method used by the server or API you’re communicating with.
Error handling and troubleshooting
Common errors when adding authorization headers
You may encounter some common errors when working with authorization headers in cURL requests using PHP. Invalid credentials, incorrect header formats, or missing or expired access tokens can cause these errors.
Invalid credentials.
One of the most common issues when using authorization headers is providing incorrect credentials, such as an API key, access token, username, or password. To resolve this issue, ensure you have entered the correct credentials and are still valid. You may need to generate or update new credentials in your code if they have been revoked or changed.
Incorrect header format.
Another common error is incorrectly formatting the authorization header. When setting the CURLOPT_HTTPHEADER option or using the CURLOPT_USERPWD option for Basic authentication, ensure that the header format follows the API provider’s guidelines. Double-check the spelling and capitalization of the header name (e.g., “Authorization”), and make sure you are using the correct delimiter (e.g., a space for “Apikey” and “Bearer” headers or a colon for Basic authentication).
Missing or expired access tokens.
For OAuth-based authentication, access tokens may be missing or expired. Access tokens typically have a limited lifespan; you must refresh them when they expire. To resolve this issue, follow the API provider’s guidelines for obtaining a new access token or refreshing an expired one.
You may need to store the refresh token securely and use it to request a new access token when needed. Make sure that the access token is correctly set in the authorization header.
To handle errors and troubleshoot issues when adding authorization headers to cURL requests in PHP, you can use the curl_error() and curl_errno() functions. These functions can provide valuable information about any errors that occurred during
Error handling using cURL error codes and error messages
CURLOPT_RETURNTRANSFER and CURLOPT_FAILONERROR options.
To enable proper error handling in your cURL requests, set the CURLOPT_RETURNTRANSFER option to true. This will return the response as a string, which can be used to check for errors. Additionally, set the CURLOPT_FAILONERROR option to true. This will cause the cURL request to return false if the HTTP response code indicates an error (e.g., 4xx or 5xx status codes).
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
Checking for errors using curl_errno() and curl_error().
After executing the cURL request, you can check for errors using the curl_errno() and curl_error() functions. curl_errno() returns the error code for the last cURL operation, while curl_error() returns a human-readable error message.
if (curl_errno($ch)) {
$errorCode = curl_errno($ch);
$errorMessage = curl_error($ch);
echo "Error Code: $errorCode\n";
echo "Error Message: $errorMessage\n";
}
Tips for troubleshooting authorization header issues
Double-check your credentials.
Make sure that your API key, access token, username, and password are correct and still valid. Regenerate or update them if necessary.
Verify the authorization header format.
Ensure that the header format follows the API provider’s guidelines, and double-check the spelling, capitalization, and delimiter used in the header.
Examine the API response.
When an error occurs, the API response may provide valuable information about the issue. Print the response using echo $response, and check for error messages or descriptions.
Consult the API documentation.
Refer to the API provider’s documentation for detailed authentication, authorization, and error-handling information. This will help you understand the requirements and limitations of the API and identify any issues with your code.
Enable verbose mode.
Enabling verbose mode in cURL can provide additional information about the request and response headers. Set the CURLOPT_VERBOSE option to true to enable verbose mode:
curl_setopt($ch, CURLOPT_VERBOSE, 1);
By following these tips and using the error handling techniques outlined above, you can effectively troubleshoot and resolve authorization header issues in cURL requests with PHP.
Best practices
When adding authorization headers to cURL requests, it’s important to follow best practices to safeguard sensitive data, handle rate limits and API restrictions, and properly close and release cURL resources.
When adding authorization headers to cURL requests, it’s important to follow best practices to safeguard sensitive data, handle rate limits and API restrictions, and properly close and release cURL resources.
Safeguarding sensitive data
When working with authorization headers in cURL requests using PHP, it is crucial to ensure the security of sensitive data, such as API keys, access tokens, and user credentials.
Using environment variables for credentials.
Storing sensitive data in environment variables is a secure way to manage credentials. Environment variables are not included in your codebase, reducing the risk of accidentally exposing them through version control or sharing.
To use environment variables in PHP, you can use the getenv() function to access the variable’s value:
$apiKey = getenv('API_KEY');
Avoid hardcoding API keys and tokens in code.
Hardcoding sensitive data, such as API keys and tokens, directly in your code is risky and not recommended. Instead, use environment variables or configuration files to store this information securely.
Handling rate limits and API restrictions
API providers often impose rate and usage restrictions to prevent abuse and ensure fair resource allocation. To handle rate limits and API restrictions:
Read the API documentation.
Understand the specific rate limits and restrictions the API provider imposes. This information is usually available in their documentation.
Implement error handling.
Check for rate limit errors in the API response and handle them accordingly. For example, if the API returns a “429 Too Many Requests” error, you can implement a retry mechanism with exponential backoff to retry the request after a specified waiting period.
Optimize your requests.
Minimize the number and frequency of API calls by caching responses, using pagination, and only requesting necessary data.
Properly closing and releasing cURL resources
When using cURL with PHP, it is essential to properly close and release resources to prevent memory leaks and other issues. Follow these best practices when working with cURL:
Close the cURL session.
After executing a cURL request, close the session by calling the curl_close() function. This releases all resources associated with the cURL handle and ensures the session is terminated correctly.
curl_close($ch);
Reuse cURL handles.
If you need to perform multiple requests, consider reusing the cURL handle instead of initializing a new one for each request. This can improve performance by reducing the overhead of creating and destroying handles.
To reuse a cURL handle, reset the options using curl_reset() before setting new options and executing another request:
curl_reset($ch);
curl_setopt_array($ch, $newOptions);
$response = curl_exec($ch);
Free memory allocated for multi-handle.
If you use the cURL multi-interface for parallel requests, cleaning up the resources associated with the multi-handle is important. After all the requests are complete, use the curl_multi_remove_handle() function to remove each cURL handle from the multi-handle, and then call curl_multi_close() to close the multi-handle:
foreach ($handles as $handle) {
curl_multi_remove_handle($mh, $handle);
}
curl_multi_close($mh);
By following these best practices for safeguarding sensitive data, handling rate limits and API restrictions, and properly closing and releasing cURL resources, you can ensure the security, efficiency, and reliability of your PHP applications that use cURL for API requests with authorization headers.
How to Add Authorization Headers to cURL Requests Summary
Adding authorization headers to cURL requests is essential to authenticating with servers and APIs to access protected resources. Several types of authorization headers include API keys, Bearer tokens (OAuth), and Basic authentication (username and password).
To add authorization headers to cURL requests in PHP, we need to define the necessary variables and include them in the CURLOPT_HTTPHEADER or CURLOPT_USERPWD options. When handling errors, we can use cURL error codes and error messages and enable error handling using the CURLOPT_RETURNTRANSFER and CURLOPT_FAILONERROR options.
Troubleshooting tips include double-checking credentials and access tokens, checking header format, error handling, and debugging using verbose cURL mode. Following these steps, we can authenticate with servers and APIs and access protected resources with cURL requests in PHP.
Continue Learning About cURL
This article is part of a more extensive series on using cURL in PHP. Feel free to browse through the articles to dig deeper into the topic.
- What is cURL used for
- Install cURL Libraries for PHP on AWS EC2 From Start to Finish
- POST cURL Body from File: PHP Code Examples ( JSON, CSV )
- How to Send a cURL GET Request
- 10 HTTP cURL Request Questions Answered
- Fetching Data from a REST API in PHP
- How to Post JSON Payload in cURL
- cURL Requests: Add Authorization Headers
- using cURL with Bearer Authorization Tokens
- using cURL with Self-Signed Certificates