Using cURL with Bearer Authorization Tokens PHP Code Examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

This article will teach you how to use cURL with Bearer Authorization Tokens in PHP. A cURL is a powerful tool that allows you to make HTTP requests and interact with APIs. Bearer Authorization Tokens are common for securing API endpoints and ensuring only authorized users have access.

How to use curl with bearer tokens

We will cover everything from setting up your environment to troubleshooting common issues and best practices. Important text will be bolded throughout the article, and relevant resources and links will be provided to deepen your understanding.

Bearer Authorization Tokens with cURL PHP Code Example 

<?php

// Replace this with your actual Bearer Token
$your_bearer_token = 'your_bearer_token_here';

// Initialize a cURL session
$curl = curl_init();

// Set cURL options
curl_setopt($curl, CURLOPT_URL, 'https://api.example.com/data/123');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $your_bearer_token,
]);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
// Uncomment and set the path to the SSL certificate file if needed
// curl_setopt($curl, CURLOPT_CAINFO, '/path/to/cacert.pem');

// Execute the cURL request
$response = curl_exec($curl);

// Decode the JSON response
$data = json_decode($response, true);

// Check for errors and handle the response
if (curl_errno($curl)) {
    echo 'cURL error: ' . curl_error($curl) . ' (' . curl_errno($curl) . ')';
} elseif (isset($data['error'])) {
    echo 'API error: ' . $data['error'];
} else {
    // Extract and display relevant data
    echo 'Data received: ' . print_r($data, true);
}

// Close the cURL session
curl_close($curl);

Steps to use Bearer Authorization Tokens with cURL

  1. Set up the environment: Ensure the cURL extension is installed, enabled, and verified in your PHP environment.
  2. Acquire a Bearer Token: Register your application with the API provider, obtain the necessary credentials (such as client ID and client secret), and generate an access token using the appropriate authentication method (e.g., OAuth 2.0).
  3. Initialize a cURL session: Create a new cURL session using the curl_init() function.
  4. Set cURL options: Configure the cURL session with necessary options, including:
  5. Execute the cURL request: Send the API request and capture the response using the curl_exec() function.
  6. Handle the response:
    • Decode the JSON response using json_decode().
    • Check for errors, such as invalid Bearer Tokens or API errors.
    • Extract and display relevant data from the decoded response.
  1. Close the cURL session: Free up resources by closing the cURL session with the  curl_close() function.

Article Highlights

  • A cURL is a powerful tool for making HTTP requests, while Bearer Tokens are commonly used for API authentication. When combined in PHP, they enable access to protected API resources.
  • To use cURL in PHP, installing, enabling, and verifying the cURL extension in your PHP environment is essential.
  • To access protected API resources, register your application with the API provider, obtain an access token, and include it in the Authorization header of your cURL requests.
  • Process API responses by decoding JSON data, checking for errors, and extracting relevant information for display or further processing.
  • Ensure a smooth experience by addressing issues like incorrect or expired Bearer Tokens, cURL errors, and SSL/TLS-related problems.
  • Enhance your cURL requests using advanced options, such as setting timeouts, customizing headers, handling redirects, and debugging requests.
  • Maintain a secure and efficient application by storing and managing tokens securely, refreshing tokens when needed, considering API client libraries and handling rate limits and throttling.
curl authorization bearer

Table of Contents

In this article, we will cover the following topics.

  1. A brief explanation of cURL and its use in PHP.
  2. The Purpose of Bearer Authorization Tokens in API Requests.
  3. Setting Up the Environment.
  4. Using Bearer Authorization Tokens with cURL.
  5. Troubleshooting Common Issues.
  6. Advanced cURL Options for Bearer Token Authorization.
  7. Best Practices for Using Bearer Tokens with cURL.
  8. Using cURL with Bearer Authorization Tokens | PHP Code Examples (2023) Summary.

A brief explanation of cURL and its use in PHP

cURL (Client URL Library) is an open-source command-line tool and software library for transferring data using various network protocols, such as HTTP, HTTPS, FTP, and more. It is widely used for interacting with web resources and APIs, making it a popular choice for developers. cURL provides robust support for handling various types of requests, including GET, POST, PUT, DELETE, and others.

In the context of PHP, the cURL library is available as an extension called libcurl. This extension lets you use cURL’s powerful features directly within your PHP scripts. By utilizing the cURL functions provided by the PHP extension, you can easily make HTTP requests to APIs, handle responses, and manipulate data. Some common use cases include:

  • Fetching data from a remote API
  • Sending data to a remote API for processing or storage
  • Authenticating with an API using various authentication methods
  • Uploading and downloading files from a remote server

In short, cURL simplifies working with web resources and APIs in PHP by providing a flexible and powerful set of functions for handling network requests and responses.

Check out our article on What is cURL Used For

The Purpose of Bearer Authorization Tokens in API Requests

Bearer Authorization Tokens are widely used to secure access to APIs and ensure that only authorized clients can interact with the protected resources. These tokens are used to authenticate and authorize clients when making API requests. The tokens are typically generated by the API provider and granted to the client after successful authentication.

The main purpose of Bearer Authorization Tokens in API requests is to:

  1. Authenticate The token acts as proof of identity for the client. When the client sends an API request with the token, the server can verify that the request comes from a legitimate source.
  1. Authorize: The token typically contains information about the client’s permissions and scope of access. When the server receives an API request with a valid token, it can determine what resources the client can access and what actions the client can perform.

By using Bearer Authorization Tokens in API requests, API providers can ensure that:

  • Only authenticated clients can access protected resources.
  • Clients are granted the appropriate level of access and permissions.
  • The security and privacy of sensitive data are maintained.

A cURL is a powerful tool for interacting with APIs in PHP, while Bearer Authorization Tokens provide a secure method for controlling access to protected API resources. Combining these two technologies allows developers to build secure and efficient applications interacting with various web services and APIs.

Setting Up the Environment

Before using PHP cURL for bearer authorization tokens, you must set up your PHP environment.

Click here for our start to finish guide on setting up cURL with PHP

Using Bearer Authorization Tokens with cURL

Now that your environment is set up let’s start using cURL with Bearer Authorization Tokens.

Acquiring a Bearer Token

To use Bearer Authorization Tokens with cURL, you first need to acquire a valid token. The process generally involves two main steps: registering an application with the API provider and generating an access token.

Step-1: Registering an application with the API provider

Before using an API, you must often register your application with the API provider. This registration process allows the provider to identify and manage access to their API by different clients. 

Here’s a general outline of the registration process:

  1. Create an account: Sign up for an account with the API provider if you don’t already have one. This account allows you to manage your applications, tokens, and permissions.
  2. Register your application: Navigate to the API provider’s developer portal or application management page once logged in. Look for an option to create or register a new application. During registration, you may need to provide information such as your application’s name, description, and website URL.
  3. Obtain API credentials: After registering your application, the API provider will usually generate a set of credentials, such as a client ID and client secret. These credentials uniquely identify your application and are used in the authentication process to obtain Bearer Tokens.
  4. Configure permissions: Depending on the API provider, you may need to configure the permissions or scopes your application requires during registration or after. These permissions determine the resources and actions your application can access and perform when using the API.

Step-2: Generating an access token

Once your application is registered and you have the necessary API credentials, you can generate a Bearer Token (access token) to authenticate and authorize your API requests. The process for obtaining a token varies depending on the API provider and their chosen authentication method. 

However, the most common methods are:

  1. OAuth 2.0: OAuth 2.0 is a widely used API authentication and authorization standard. In an OAuth 2.0 flow, your application exchanges its client credentials for an access token, which is then used to authenticate API requests. The specific OAuth 2.0 flow you’ll use depends on the API provider and your application’s use case. Some common flows include the authorization code flow, client credentials flow, and password grant flow.
  2. API key: Some API providers use a simpler API key-based authentication method. In this case, you’ll receive an API key when registering your application. This key is then included in your API requests as a query parameter or in the request headers. Depending on the provider, you might need to exchange the API key for a Bearer Token before making API requests.
  3. Custom authentication: Some API providers use custom authentication methods that don’t follow standard patterns like OAuth 2.0 or API keys. In such cases, refer to the provider’s documentation for specific instructions on obtaining a Bearer Token.

After completing the authentication process, you will receive a Bearer Token, which you can use to authenticate and authorize your cURL requests in PHP. Remember to store your token and API credentials securely, as they should be treated as sensitive information.

Making an API request using cURL and Bearer Token 

Once you have acquired a Bearer Token, you can make API requests using cURL in PHP. 

The process involves:

  • Initializing a cURL session.
  • Setting cURL options.
  • Executing the request.
  • Handling the response.
  • Closing the cURL session.

Let’s explore each step in detail.

Step-1: Initializing a cURL session

To start a cURL session, use the curl_init() function. This function initializes a new cURL handle, which you’ll use to configure and execute your API request.

$curl = curl_init();

Step-2: Setting cURL options

Next, configure the cURL session by setting various options using the curl_setopt() function. Some common options to set include:

  1. Specifying the URL endpoint

Provide the API endpoint you want to access, replacing placeholders with actual values, if necessary.

curl_setopt($curl, CURLOPT_URL, 'https://api.example.com/data/123');
  1. Setting the request method

Specify the HTTP method for your request, such as GET, POST, PUT, or DELETE.

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
  1. Adding the Bearer Token to the Authorization header

Include your Bearer Token in the request’s Authorization header to authenticate and authorize the request.

curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $your_bearer_token,
]);
  1. Enabling SSL (if required)

If the API endpoint uses HTTPS, enable SSL verification for a secure connection. You can also provide the path to the SSL certificate file if necessary.

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_CAINFO, '/path/to/cacert.pem');

Step-3: Executing the cURL request

Execute the cURL request by calling the curl_exec() function, which returns the API response as a string.

$response = curl_exec($curl);

Step-4: Handling the response

  1. Decoding the JSON response

APIs typically return data in JSON format. Use the json_decode() function to convert the JSON response into a PHP object or array.

$data = json_decode($response, true);
  1. Checking for errors

Check for any cURL or API errors, handling them as needed. If an error occurs, use the curl_error() and curl_errno() functions to retrieve the error message and code, respectively.

if (curl_errno($curl)) {
    echo 'cURL error: ' . curl_error($curl) . ' (' . curl_errno($curl) . ')';
} elseif (isset($data['error'])) {
    echo 'API error: ' . $data['error'];
} else {
    // No errors, proceed to process the data
}
  1. Extracting and displaying relevant data

Access and display the data from the API response according to your application’s requirements.

echo 'Data received: ' . print_r($data, true);

Step-5: Closing the cURL session

Finally, close the cURL session using the curl_close() function to free up resources.

By following these steps, you can make an API request using cURL and a Bearer Token in PHP, securely authenticating and authorizing your requests while interacting with the API.

Complete PHP code Example

Here is a complete example of a PHP script that uses cURL and a Bearer Token to make an API request:

<?php

// Replace this with your actual Bearer Token
$your_bearer_token = 'your_bearer_token_here';

// Initialize a cURL session
$curl = curl_init();

// Set cURL options
curl_setopt($curl, CURLOPT_URL, 'https://api.example.com/data/123');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $your_bearer_token,
]);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
// Uncomment and set the path to the SSL certificate file if needed
// curl_setopt($curl, CURLOPT_CAINFO, '/path/to/cacert.pem');

// Execute the cURL request
$response = curl_exec($curl);

// Decode the JSON response
$data = json_decode($response, true);

// Check for errors and handle the response
if (curl_errno($curl)) {
    echo 'cURL error: ' . curl_error($curl) . ' (' . curl_errno($curl) . ')';
} elseif (isset($data['error'])) {
    echo 'API error: ' . $data['error'];
} else {
    // Extract and display relevant data
    echo 'Data received: ' . print_r($data, true);
}

// Close the cURL session
curl_close($curl);

The above code initializes a cURL session, sets the necessary options, executes the request, handles the response, and closes the session. 

Make sure to replace ‘your_bearer_token_here’ with your actual Bearer Token before running the script.

Troubleshooting Common Issues using cURL with Bearer Tokens

You might encounter some common issues when working with cURL and Bearer Tokens in PHP. 

Here are explanations and potential solutions for some of these problems:

Incorrect Bearer Token

An incorrect Bearer Token can cause authentication failures and result in access denied or unauthorized error messages from the API. 

To address this issue:

  1. Double-check the token: Ensure you use the correct Bearer Token for the API you’re accessing. Verify the token against the one provided by the API provider.
  2. Verify token format: Ensure you use the correct format when including the token in the Authorization header. It should be in the form Authorization: Bearer <your_token>.

Expired Bearer Token

Bearer Tokens often have a limited lifespan and expire after a certain period. When a token expires, you must obtain a new one to continue accessing the API. 

To handle expired tokens:

  1. Check token expiration: Many APIs include an expiration timestamp or duration in the token response. Monitor this information to determine when a token will expire.
  2. Refresh tokens: Some API providers implement OAuth 2.0 refresh tokens, which allow you to obtain a new access token without requiring the user to re-authenticate. If the API supports refresh tokens, use them to automatically acquire a new access token when the current one expires.
  3. Re-authenticate: If the API doesn’t support refresh tokens, you may need to re-authenticate using the appropriate method (e.g., client credentials flow or authorization code flow) to obtain a new access token.

cURL errors and their meanings

cURL errors can occur for various reasons, such as network issues, incorrect settings, or SSL/TLS errors. When an error occurs, use the curl_error() and curl_errno() functions to retrieve the error message and code, respectively. You can refer to the cURL error codes documentation for a comprehensive list of error codes and their meanings.

SSL/TLS-related issues

Secure connections (HTTPS) with cURL may encounter SSL/TLS issues, which can cause errors or prevent the request from being executed. 

Some common SSL/TLS issues and their solutions include:

  1. Verify SSL settings: Ensure you have enabled SSL verification using the CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST options. Setting these options to true and 2 will ensure secure connections.
  2. Certificate authority bundle: In some cases, cURL may not have access to the necessary certificate authority (CA) bundle to verify SSL certificates. If so, you can download a CA bundle (e.g., from Mozilla’s CA bundle) and specify its path using the CURLOPT_CAINFO option.
  3. Outdated SSL/TLS library: If you continue to experience SSL/TLS issues, check if your cURL library or PHP installation uses an outdated SSL/TLS library. You may need to update your PHP installation or recompile cURL with support for a more recent SSL/TLS library, such as OpenSSL.

By addressing these common issues, you can ensure a smoother experience when using cURL and Bearer Tokens in your PHP applications.

Advanced cURL Options for Bearer Token Authorization

When using cURL with Bearer Tokens in PHP, you might want to utilize some advanced cURL options for better control over your API requests. 

Here’s a detailed explanation of some useful options:

Setting timeouts for cURL requests

Timeouts can prevent your application from waiting indefinitely for a response from the API, which may occur if the API is slow or unresponsive. 

To set timeouts for cURL requests, you can use the following options:

  1. Connection timeout: Use the CURLOPT_CONNECTTIMEOUT option to specify the maximum time in seconds that cURL should spend trying to connect to the API server.
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10); // 10 seconds
  1. Total timeout: Use the CURLOPT_TIMEOUT option to set the maximum time in seconds that cURL should allow for the entire request, including connecting and transferring data.
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 30 seconds

Customizing HTTP headers

You can customize the HTTP headers sent with your cURL request using the CURLOPT_HTTPHEADER option. This option allows you to add, modify, or remove headers as needed. To set custom headers, pass an array of header strings to the CURLOPT_HTTPHEADER option.

curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $your_bearer_token,
    'Accept: application/json',
    'Custom-Header: custom-value',
]);

Handling redirects

APIs might sometimes return a redirect response, requiring your application to follow the redirect to access the requested data. 

To automatically follow redirects with cURL, set the CURLOPT_FOLLOWLOCATION option to true:

curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

You can also limit the number of redirects that cURL will follow using the CURLOPT_MAXREDIRS option:

curl_setopt($curl, CURLOPT_MAXREDIRS, 3); // Allow up to 3 redirects

Debugging cURL requests

When troubleshooting cURL requests, it can be helpful to capture detailed information about the request and response. 

You can enable verbose mode in cURL by setting the CURLOPT_VERBOSE option to true:

curl_setopt($curl, CURLOPT_VERBOSE, true);

By default, the verbose output is sent to stderr. To capture the verbose output in a variable, you can use the CURLOPT_STDERR option along with a temporary stream:

$tempStream = fopen('php://temp', 'rw+');
curl_setopt($curl, CURLOPT_STDERR, $tempStream);

After executing the cURL request, you can rewind the temporary stream and read its contents:

rewind($tempStream);
$verboseOutput = stream_get_contents($tempStream);

These advanced cURL options can help you fine-tune your API requests, manage timeouts, customize headers, handle redirects, and debug issues when using Bearer Token Authorization in PHP.

Best Practices for Using Bearer Tokens with cURL

To ensure a secure and efficient experience when using Bearer Tokens with cURL in PHP, it’s essential to follow some best practices. 

Here are some key considerations:

Storing and managing Bearer Tokens securely

Bearer Tokens are sensitive credentials that should be protected from unauthorized access. To store and manage them securely:

  1. Environment variables: Store Bearer Tokens in environment variables instead of hardcoding them in your PHP scripts. This approach keeps tokens out of your source code, reducing the risk of accidental exposure.
$your_bearer_token = getenv('API_BEARER_TOKEN');
  1. Access controls: Restrict access to the environment or configuration files containing your Bearer Tokens. Use file permissions and access control mechanisms to ensure that only authorized users and processes can access these sensitive files.
  1. Encryption: Consider encrypting Bearer Tokens at rest and decrypting them when needed. This approach adds an extra layer of security, making it more difficult for an attacker to access the tokens even if they gain access to the storage location.

Refreshing Bearer Tokens when necessary

Bearer Tokens often have a limited lifespan and must be refreshed or replaced when they expire. 

To handle token refreshes:

  1. Monitor expiration: Track the token’s expiration timestamp or duration, if provided by the API, and refresh it before it expires.
  2. Use refresh tokens: If the API supports OAuth 2.0 refresh tokens, use them to obtain new access tokens without requiring the user to re-authenticate. This approach simplifies token management and improves the user experience.
  3. Handle token refresh errors: Ensure your application gracefully handles errors that may occur during token refreshes, such as network issues or API errors.

Using an API client library

Instead of manually implementing API requests with cURL, consider using an API client library for the specific API you’re accessing. API client libraries often handle authentication, token management, error handling, and other tasks, simplifying your code and reducing the risk of errors.

Rate limiting and throttling considerations

Many APIs enforce rate limits or throttling to prevent abuse and manage server resources. 

To handle these limitations:

  1. Respect rate limits: Monitor and adhere to the rate limits imposed by the API. Exceeding these limits may result in temporary or permanent bans.
  2. Implement retries: Implement a retry mechanism with exponential backoff to handle occasional rate limit errors or throttling.
  3. Caching: Cache API responses when appropriate to reduce the number of requests and minimize the impact of rate limits.

By following these best practices, you can ensure a secure, efficient, and reliable experience when using Bearer Tokens with cURL in your PHP applications.

Using cURL with Bearer Authorization Tokens

Combining cURL with Bearer Tokens in PHP offers an efficient and secure way to access protected API resources. Adhering to best practices and security measures results in a reliable and robust application.

This article thoroughly guides using cURL and Bearer Authorization Tokens in PHP to access protected API resources securely. It covers the entire process, from setting up the PHP environment and acquiring Bearer Tokens to making API requests and handling responses. 

The article also addresses troubleshooting common issues, explores advanced cURL options, and emphasizes best practices for securely managing tokens and handling rate limits.

By following the steps and recommendations provided, developers can effectively utilize cURL and Bearer Tokens in their PHP applications to confidently access APIs and build robust, secure, and efficient applications.

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.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.