0

How can I use Restful API using file_get_contents and Digest Authentication in php.

I know I can access it using curl

$ch = curl_init('http://webservicesurlhere.com');


curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
        //,
        //'Content-Length: ' . strlen($data_string)
        )
);

$resources = curl_exec($ch);
curl_close($ch);

But my Current code is written using file_get_contents Basic type authentication can be accessed using below code

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => "Content-Type: text/xml\r\n".
      "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
    'content' => $body,
    'timeout' => 60
  )
);

$context  = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);

Does anyone knows, How can I use file_get_contents for Digest type of authentication?

Related information which I find.

How to post data in PHP using file_get_contents?

Call a REST API in PHP

Community
  • 1
  • 1
Developer
  • 21,956
  • 19
  • 72
  • 119

2 Answers2

0

As you said, the following code using curl should work:

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, 'user:secret');

However, curl does the whole work for you. When using file_get_contents() you need to implement digest authentication on your own. Sorry, have no time to prepare an example now, but I hope this helps http://www.ietf.org/rfc/rfc2617.txt, http://freestyle-developments.co.uk/blog/?p=61 ...

Maybe I will also add a custom example later here, because I always wanted to have a closer look at digest auth...

hek2mgl
  • 133,888
  • 21
  • 210
  • 235
0

This work form me over https and with a json response

<?php 
 $login = 'USUARIO';
 $password = '123';
 $url = 'https://ww.google.com/datos-feps?date=13-08-2020';
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL,$url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
 $result_json = curl_exec($ch);
 curl_close($ch);    
 echo $result_json;      
?>
Doberon
  • 443
  • 4
  • 14