PHP 基本身份验证 file_get_contents()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30628361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP basic auth file_get_contents()
提问by dehniz
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).
我需要从网站解析一些 XML 数据。XML 数据采用原始格式,但在我需要进行身份验证之前(基于基本网络服务器的身份验证,使用用户名和密码)。
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
无法打开流:HTTP 请求失败!HTTP/1.0 401 未经授权
PHP seems to have problems with the authentification. Any idea how to fix this?
PHP 的身份验证似乎有问题。知道如何解决这个问题吗?
回答by miken32
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()
:
您将需要添加流上下文以获取请求中的额外数据。尝试类似以下未经测试的代码。它基于以下 PHP 文档中的示例之一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 );