Logo
Code Ranks ×

PHP cURL Part 5(Authentication) |Coderank

09/04/2019  .   1 minute, 45 seconds to read  .   Posted by Admin
#php #curl #phpcurl #learnphp #phpframework #phpcrud #phptutorial #phpfunctions

So far, we've learned the following features of PHP cURL in this series of articles.

  1. PHP cURL Basics
  2. Getting Contents of any URL
  3. Downloading File from URL
  4. Checking URL existence
  5. Form Submission

Authentication Using PHP cUrl

In this article, we'll learn how to perform HTTP Basic Authentication using PHP cURL. Sometimes, we secure some resources of the website so only authorized users can access them. We can access those resources programmatically by passing username and password in curl request.

$username = "john";
$password = "12345";
$curl = curl_init("https://httpbin.org/post");
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
curl_close($curl);
echo '<pre>',$result;

Explanation:

In our previous articles, we've used CURLOPT_URL to set target URL but we can pass that URL directly in curl_init() as displayed above. Most of the cURL options have been discussed in our previous parts of the article. Here is a short description

  1. CURLOPT_RETURNTRANSFER: used to direct cURL to not display response(default) but return after execution.
  2. CURLOPT_SSL_VERIFYPEER: used to enable or disable SSL.
  3. CURLOPT_POST:  used to perform post request.

We've used a new option in this article.

CURLOPT_USERPWD

CURLOPT_USERPWD option is used to pass the username and password with the request. The format for passing username and password is Username:Password. it takes username and password, generate their base64 and pass the final string in the header as follows:

{"Authorization": "Basic am9objoxMjM0NQ=="}

Note:
am9objoxMjM0NQ== is base64 of john:12345

Response:

HTTP Bin is used to test HTTP requests. It returns the request data as a response, you can see we got all of our data in the response.

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Authorization": "Basic am9objoxMjM0NQ==", 
    "Content-Length": "0", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org"
  }, 
  "json": null, 
  "origin": "103.255.6.81, 103.255.6.81", 
  "url": "https://httpbin.org/post"
}

That's all for this part of the article. In the next part, we'll learn to save and send cookies using PHP cURL.

Thanks for reading.