23

I need to parse some XML data from a website. The XML data is in raw format, but before I need to authentificate (basic webserver based auth, with username & password).

I tried:

$homepage = file_get_contents('http://user:password@IP:PORT/folder/file');

but I get the following error:

failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized

PHP seems to have problems with the authentification. Any idea how to fix this?

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
dehniz
  • 235
  • 1
  • 2
  • 6

1 Answers1

77

You will need to add a stream context to get the extra data in your request. Try something like the following untested code. It's based on one of the examples on the PHP documentation for file_get_contents():

$auth = base64_encode("username:password");
$context = stream_context_create([
    "http" => [
        "header" => "Authorization: Basic $auth"
    ]
]);
$homepage = file_get_contents("http://example.com/file", false, $context );
miken32
  • 42,008
  • 16
  • 111
  • 154