PHP basic auth file_get_contents ()
I need to parse some XML data from a website. The XML data is in raw format, but before I need to authenticate (basic auth, with username and password).
I tried:
$homepage = file_get_contents('http://user:password@IP:PORT/folder/file');
but I am getting the following error:
failed to open stream: HTTP request failed! HTTP / 1.0 401 Unauthorized
PHP seems to have authentication issues. Any idea how to fix this?
+3
dehniz
source
to share
1 answer
You will need to add a stream context to get additional data in the request. Try something like the following untested code. It is based on one of the PHP documentation examples 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 );
+8
miken32
source
to share