简体   繁体   中英

How to Access REST Web service using file_get_contents with Digest Authentication in php

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

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...

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;      
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM