PHP Curl Request With Bearer Token Authorization Header Example
This simple article demonstrates of php curl request with bearer token. i explained simply about curl post request with bearer token php. this example will help you rest api token based authentication example php. This tutorial will give you simple example of php curl with authorization header. Alright, let’s dive into the steps.
In this example, we will use CURLOPT_HTTPHEADER to pass authorization: bearer token for authorization. so let’s see bellow simple example code here:
/* API URL */
$url = ‘http://www.mysite.com/api’;
/* Init cURL resource */
$ch = curl_init($url);
/* Array Parameter Data */
$data = [‘name’=>’Hardik’, ’email’=>’itsolutionstuff@gmail.com’];
/* pass encoded JSON string to the POST fields */
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
/* set the content type json */
$headers = [];
$headers[] = ‘Content-Type:application/json’;
$token = «your_token»;
$headers[] = «Authorization: Bearer «.$token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
/* set return type json */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* execute request */
$result = curl_exec($ch);
/* close cURL resource */
curl_close($ch);
?>
Hardik Savani
I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- PHP Curl Delete Request Example Code
- PHP Curl POST Request with Headers Example
- PHP Curl Get Request with Parameters Example
- PHP Curl Request with Certificate (cert pem file option) Example
- How to Generate 4,6,8,10 Digit Random number in PHP?
- PHP Get All Array Keys Starting with Certain String Example
- PHP Convert XML to JSON Example
- Codeigniter Curl Post Request with Parameters Example
- PHP CURL Post Request with Parameters Example
- Laravel CURL Request Example using Ixudra/curl
- PHP Download File from URL using CURL Request Example
How to get Authorization header in PHP
In order to construct a secure resource that can be accessed through an API, we must utilize an authorization header with a token or bearer. In this article, I will guide you how to obtain the authorization header, extract the token or bearer. Then authenticate it against a database table and return a JSON output in PHP.
Here is what I have on my system.
PHP already has a built-in function, getallheaders(), that can retrieve all headers. It is useful because it eliminates the need for additional code to be written.
The next step is to check if the key exists in the array. We will use the array_key_exists function. If it does not exist, return an error.
if (!array_key_exists('Authorization', $headers)) < echo json_encode(["error" =>"Authorization header is missing"]); exit; >
In most cases, the token has a keyword of your choice, such as ‘Token‘ or ‘Bearer‘. To check this, we will use the substr function.
if (substr($headers['Authorization'], 0, 6) !== 'Token ') < echo json_encode(["error" =>"Token keyword is missing"]); exit; >
if (substr($headers['Authorization'], 0, 7) !== 'Bearer ') < echo json_encode(["error" =>"Bearer keyword is missing"]); exit; >
Now we will extract the actual token. This is for Token keyword.
$token = trim(substr($headers['Authorization'], 6));
We will also need to check the validity of the token against a database table. I am using my own framework for this purpose, but you can also accomplish this by connecting to the database and running a query similar to the following:
$host = "host"; $dbname = "database"; $username = "username"; $password = "password"; $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT COUNT(t.token) as totalRows FROM tokens as t WHERE t.token = :token"; $data = [ "token" => $token ]; $stmt = $conn->prepare($query); $stmt->execute($data); $result = $stmt->fetch(PDO::FETCH_ASSOC); $count = $result['totalRows'];
$host = "host"; $dbname = "database"; $username = "username"; $password = "password"; $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $headers = getallheaders(); if (!array_key_exists('Authorization', $headers)) < echo json_encode(["error" =>"Authorization header is missing"]); exit; > else < if (substr($headers['Authorization'], 0, 6) !== 'Token ') < echo json_encode(["error" =>"Token keyword is missing"]); exit; > else < $token = trim(substr($headers['Authorization'], 6)); $query = "SELECT COUNT(t.token) as totalRows FROM tokens as t WHERE t.token = :token"; $data = [ "token" =>$token ]; $stmt = $conn->prepare($query); $stmt->execute($data); $result = $stmt->fetch(PDO::FETCH_ASSOC); $count = $result['totalRows']; if ($count == 0) < echo json_encode(["error" =>"Authorization failed"]); exit; > else < ## continue the rest of your stuff >> >
If you are using Bearer keyword, remember to change the position to 7 in substr function.
Something like this will work.
$token = trim(substr($headers['Authorization'], 7));
wildiney / bearer-token.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* ALERT! There are more than ten years since I wrote the first version (adaptation) of this code with PHP 5.6, |
* then I changed my code stack and I couldn’t mantain this code anymore. Ten years ago worked like a charm. |
* Fell free to test, use, fork, update, etc. and if possible put in the comments how to fix, |
* if it doesn’t work for you as it is, so other people could find answers. |
**/ |
/** |
* Get hearder Authorization |
**/ |
function getAuthorizationHeader () |
$ headers = null ; |
if (isset( $ _SERVER [ ‘Authorization’ ])) |
$ headers = trim( $ _SERVER [» Authorization «]); |
> |
else if (isset( $ _SERVER [ ‘HTTP_AUTHORIZATION’ ])) < //Nginx or fast CGI |
$ headers = trim( $ _SERVER [» HTTP_AUTHORIZATION «]); |
> elseif (function_exists( ‘apache_request_headers’ )) |
$ requestHeaders = apache_request_headers(); |
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don’t care about capitalization for Authorization) |
$ requestHeaders = array_combine(array_map( ‘ucwords’ , array_keys( $ requestHeaders )), array_values( $ requestHeaders )); |
//print_r($requestHeaders); |
if (isset( $ requestHeaders [ ‘Authorization’ ])) |
$ headers = trim( $ requestHeaders [ ‘Authorization’ ]); |
> |
> |
return $ headers ; |
> |
/** |
* get access token from header |
* */ |
function getBearerToken () |
$ headers = getAuthorizationHeader(); |
// HEADER: Get the access token from the header |
if (!empty( $ headers )) |
if (preg_match( ‘/Bearer\s(\S+)/’ , $ headers , $ matches )) |
return $ matches [ 1 ]; |
> |
> |
return null ; |
> |