首页 > 解决方案 > 将 file_get_contents 与基本身份验证和 SSL 一起使用

问题描述

我正在尝试GET使用 SSL 的请求和使用以下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. 叫我疯子。

标签: phpfile-get-contents

解决方案


好奇心是一件好事,所以在解决这个问题之前不回退到 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中使用的默认协议版本是 1.0。这就是您收到错误 500 的原因。


推荐阅读