【问题标题】:Using file_get_contents with basic auth and SSL将 file_get_contents 与基本身份验证和 SSL 一起使用
【发布时间】:2018-11-10 23:10:12
【问题描述】:

我正在尝试使用 SSL 的 GET 请求和使用 file_get_contents 函数的基本身份验证:

$username = "XXXXXXXXXX";
$password = "XXXXXXXXXX";

$url = "https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api";

$context = stream_context_create(array("http" => array("header" => "Authorization: Basic " . base64_encode("$username:$password"))));

$data = file_get_contents($url, false, $context);

echo $data;

这是我收到的错误消息:

警告:file_get_contents(https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api):打开流失败:HTTP 请求失败! HTTP/1.0 500 服务器错误...

我已经确认openssl 已启用:

我们不妨提前解决这个问题:

为什么不直接使用 cURL?

我可以。但我也想弄清楚为什么file_get_contents 不起作用。我喜欢file_get_contents 的相对简单。叫我疯子。

【问题讨论】:

  • 使用其他没有基本身份验证的 HTTPS URL,是否有效?
  • 我可以用我的浏览器点击 url,我不能用 file_get_contents,我怀疑他们正在检测自动尝试。使用 curl 你可以让它看起来更像是一个“真实的”人访问,你没有file_get_contents的那些选项@
  • @AnthonyB 是的,例如,它适用于 https://google.com
  • @smith 很有趣......所以它可能是这个端点独有的?我将尝试一个基本的 cURL 设置,看看我是否遇到了同样的问题。
  • 这是我的猜测,我只是为你做了一些基本的测试。

标签: php file-get-contents


【解决方案1】:

好奇心是一件好事,所以在解决这个问题之前不回退到 cURL 来挖掘这个问题是很酷的。

<?php
$username = "XXXXXXXXXX";
$password = "XXXXXXXXXX";

$url = "https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api";

$context = stream_context_create(array(
    "http" => array(
        "header" => "Authorization: Basic " . base64_encode("$username:$password"),
        "protocol_version" => 1.1, //IMPORTANT IS HERE
    )));

$data = file_get_contents($url, false, $context);

echo $data;

事实上服务器不支持 HTTP/1.0。所以你对 SSL/TLS 和你的用户代理没有任何问题。它只是从 1.1 开始支持 HTTP 的服务器。

正如stream_context_create 文档中所说,stream_context_create 中使用的默认 protocol_version 是 1.0。这就是您收到错误 500 的原因。

【讨论】:

  • 这成功了! +1 并接受。我不清楚为什么有人投反对票...
  • 我不知道为什么有人投了反对票,我希望他/她发表评论。但是谢谢,我很高兴为您提供帮助!
【解决方案2】:

编辑:我的错,看不出这不是卷曲。试试这个

$username = "XXXXXXXXXX";
$password = "XXXXXXXXXX";

$url = "https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api";

$context = stream_context_create(array(
"http" => array("header" => "Authorization: Basic " . base64_encode("$username:$password")), 
"ssl"=>array(
    "verify_peer"=>false,
    "verify_peer_name"=>false,
)));

$data = file_get_contents($url, false, $context);

echo $data;

【讨论】:

  • 你测试了吗?在将代码发布为“答案”之前测试您的代码是个好主意
  • 没有登录无法测试,无法直接评论
  • 如果您不确定,请发表评论而不是答案。我已经测试了你的代码,我得到错误 500 作为 OP。如果您的解决方案是您的解决方案,由于凭据无效,我们会收到错误 401。
  • 我知道,但我不能评论 (
  • 感谢您的宝贵时间,但此解决方案不起作用。
猜你喜欢
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-01
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多