How To Make A PHP Curl Request With Basic Authentication Example
Teams applying “How To Make A PHP Curl Request With Basic Authentication Example” in a production project can use the official example to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the PHP project and test it against the project’s actual database and runtime.
Hi guys,
Today i will explained to the How To Make A PHP Curl Request With Basic Authentication. This example is so easy to use in php.
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.
So let's start to the example and follow to the my all step.
Example :
<?php
$url = 'https://api.example.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.example.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. If you like the article,like our Facebook page and follow us on Twitter.
finally resize to the your file in your folder.
So, finally we are done with our code we can get below output.
- How To Use Php Conditional Statement Example
- How to Check if String Contains Regex in PHP?
- PHP Array_column() Function Example
- PHP Generate List of Random Numbers Between 0 and 100 Example
- How to User Login with Facebook in PHP?
- How to Explode Every Character into Array Using PHP Example?
- PHP Form Validation Tutorial
- PHP Convert XML to JSON Example