When accessing API request over PHP curl, some routes are authentication required. Also third party API mostly required to authenticate before accepting request. This can be done by Bearer or Basic authentication method.
In this article, we will see how to send PHP curl request on authentication protected url. You need to send user and password data with the request. Below example send the get request which requires basic authentication:
<?php
$url = 'https://api.laravelcode.com/my-activity';
$username = '[email protected]';
$password = '123456';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You can also send curl request using Authorization header. Curl CURLOPT_USERPWD option basically send Authorization header with value of username:password in a base64 format. You can do it as below:
<?php
$url = 'https://api.laravelcode.com/my-activity';
$username = '[email protected]';
$password = '123456';
$headers = array(
'Authorization: Basic '. base64_encode($username.':'.$password)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
This way, you can also make curl request over the routes which requires authentication.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to move an element into another element using jQuery
Use the jQuery .appendTo() Method You...Data scraping with node js and display in laravel
Hello, Everyone laravelcode today share...How to Validate Textbox to Accept only Characters in Javascript
In this article, we will see how to allo...Laravel 5.4 Users Authorization With Spatie Laravel-Permission
Today, Laravelcode share with you a very...An error occurred during the signature verification. The following signatures were invalid
Sometimes, while updating repository key...