php 文件获取内容无法打开未经授权的流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3566487/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:15:16  来源:igfitidea点击:

File-get-contents failed to open stream Unauthorized

phphttphttpwebrequestfile-get-contents

提问by Aaron

I am trying to use file_get_contents.I have made sure that allow_url_fopen is enabled in php.ini. As of now it is telling me:

我正在尝试使用 file_get_contents。我已确保在 php.ini 中启用了 allow_url_fopen。截至目前,它告诉我:

[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

[function.file-get-contents]:无法打开流:HTTP 请求失败!HTTP/1.1 401 未经授权

All I'm doing is the following, which I can access through browser without a problem.

我正在做的就是以下内容,我可以通过浏览器毫无问题地访问它。

$url=('http://site/@api/users/[email protected]/properties');
$xmlString=file_get_contents($url);

I believe this is an authentication issue but not sure how I can supply the proper credentials from within the script itself. Any ideas would be greatly appreciated.

我相信这是一个身份验证问题,但不确定如何从脚本本身提供正确的凭据。任何想法将不胜感激。

回答by Cfreak

In your url try:

在您的网址中尝试:

http://user:password@site/ 

(append whatever the rest of the URL for your API should be)

(附加 API 的其余 URL 应该是什么)

回答by Raoul Duke

Just put the user info into the URL:

只需将用户信息放入 URL:

$url = 'http://user:[email protected]/foo/bar/whatever';

回答by Frxstrem

The 401 Unauthorizedstatus code means that you should have authenticated, but that you haven't, or that you have authenticated with the wrong credentials. It is most commonly used when using HTTP authentication, which is authentication built into the HTTP protocol, and therefore is universal, not only for HTML documents, but for anything transfered over the HTTP protocol.

401 Unauthorized状态代码表示您应该通过身份验证,但你没有,或者你已经用错误的证书进行身份验证。它在使用 HTTP 身份验证时最常用,HTTP 身份验证是内置于 HTTP 协议中的身份验证,因此是通用的,不仅适用于 HTML 文档,还适用于通过 HTTP 协议传输的任何内容。

To authenticate with HTTP authentication, simply add username:password@before the hostname in the URL. For instance:

要使用 HTTP 身份验证进行身份验证,只需username:password@在 URL 中的主机名之前添加。例如:

http://foobar:[email protected]/passwordprotected/

http://foobar:[email protected]/passwordprotected/

This would request the /passwordprotected/directory from example.comwith the username foobarand the password mysupersecretpassword.

这将使用用户名和密码请求/passwordprotected/目录。example.comfoobarmysupersecretpassword

It's not any worse than that. :)

没有比这更糟糕的了。:)