PHP基本身份验证file_get_contents() [英] PHP basic auth file_get_contents()
问题描述
我需要从网站解析一些XML数据. XML数据为原始格式,但是在我需要进行身份验证之前(基于基本网络服务器的身份验证,使用用户名和密码).
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).
我尝试过:
$homepage = file_get_contents('http://user:password@IP:PORT/folder/file');
但出现以下错误:
无法打开流:HTTP请求失败! HTTP/1.0 401未经授权
failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
PHP似乎在身份验证方面存在问题.知道如何解决这个问题吗?
PHP seems to have problems with the authentification. Any idea how to fix this?
推荐答案
您将需要添加流上下文以获取请求中的额外数据.尝试类似以下未经测试的代码.它基于file_get_contents()
的PHP文档上的示例之一:
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 );
这篇关于PHP基本身份验证file_get_contents()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!