【发布时间】:2017-07-04 12:05:34
【问题描述】:
我正在用 PHP 创建一个 API 端点,并有一个输出 JSON 的页面,我们称之为example.com/stats。当用户尝试返回数据时,只有在他们使用file_get_contents() 时才会成功,当用户尝试使用 cURL 访问它时,他们会收到 NULL 响应。我应该如何在 PHP 中提供 JSON 数据以使其与 file_get_contents 和 curl 兼容?
更多信息如下。
/stats 的来源
header('Content-type: application/json');
echo '{"status":"error", "message":"invalid operation"}';
当我尝试通过file_get_contents() 从另一台服务器读取此页面时,一切正常。
function fgc($receive_url){
$fgc = json_decode(file_get_contents($receive_url), true);
return $fgc;
}
$out = fgc("https://example.com/stats");
var_dump($out);
//returns: array(2) { ["status"]=> string(5) "error" ["message"]=> string(17) "invalid operation" }
当我尝试做同样的事情但使用 cURL 时,我得到 NULL。
function curlit($receive_url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $receive_url);
$ccc = curl_exec($ch);
$json = json_decode($ccc, true);
return $json;
}
$out = curlit("https://example.com/stats");
var_dump($out);
请注意,其他显示 JSON 的网站可以正常使用我的 cURL 函数,特别是我从 example.com/stats 提供的数据在使用 cURL 时会失败。我认为使用标头 application/json 足以允许通过 cURL 访问这些数据。有什么想法在发球方面可能出问题吗?为什么文件可以获取内容但不能卷曲?也许 cURL 在页面加载完成之前显示结果?我尝试删除 application/json 标头,但这没有任何区别。
【问题讨论】:
-
是 http 还是 https 的 URL?
-
HTTPS。
example.com上的 SSL 处于活动状态并通过 cloudflare 启用。 -
您可以尝试使用 CLI 版本的 cURL 看看是否有效吗?
-
另外,尝试添加这个 cURL 选项
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); -
如果这不起作用,只需使用
curl_error检索有关哪个部分失败的更多信息