1

I'm using the following commands to read a remote XML file in a PHP web page:

    $url = 'http://www.examplesite.com/xml';
    $xml = simplexml_load_file($url);

Unfortunately, the site uses digest authentication and a username/password box normally pops up and requires me to log into the site. It does not work to embed my username and password in the URL itself (like http://USER:PASSWORD@examplesite.com/), nor is this very secure.

How do I authenticate (in PHP) to get the XML file?

Alligator
  • 691
  • 3
  • 11
  • 21
  • possible duplicate of [How to post http request using digest authentication with libcurl](http://stackoverflow.com/questions/16800640/how-to-post-http-request-using-digest-authentication-with-libcurl) – Marc B Oct 10 '13 at 18:24
  • I have no idea what that other post is talking about. I'm using PHP and the simplexml element. – Alligator Oct 10 '13 at 18:30
  • note the **SIMPLE** in simplexml. Doing digest authentication is **NOT** its job. Fetching remote xml is just a side effect of how PHP operates. – Marc B Oct 10 '13 at 18:36

1 Answers1

0
function get($url, $user, $pass) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
    curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $res = curl_exec();
    curl_close($ch);
    return $res;
}

You can do this with cURL. Note that first 3 curl flags - forbid reuse, fresh connect, follow location, are probably not needed but may be required in some cases(a 302 post auth etc.).

Prasanth
  • 5,230
  • 2
  • 29
  • 61
  • I continue to get a "401 - Unauthorized" response with this, even with a good URL, username, and password. I had someone else test it with cURL 7.21.6 and they claimed it worked. My version of cURL is 7.30.0. Are there specific cURL settings I need to enable on my server to make this work? – Alligator Oct 11 '13 at 14:50
  • I tried a shell connection and I can authenticate using digest just fine. I'm not sure why the PHP version cannot authenticate. – Alligator Oct 11 '13 at 15:03