【问题标题】:Page readable by file_get_contents but not cURLfile_get_contents 可读但 cURL 不可读的页面
【发布时间】: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 检索有关哪个部分失败的更多信息

标签: php json api


【解决方案1】:

添加的答案供参考:

用OP调试后发现example.com发出301重定向。

解决方案是通过添加以下选项使 cURL 跟随重定向:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

【讨论】:

    【解决方案2】:

    可能您的服务器禁用了 cURL,请尝试使用 function_exists 进行检查:

    var_dump(function_exists('curl_version'));
    

    【讨论】:

    • cURL 已启用,我可以通过相同的 cURL 功能访问其他站点。特别是 example.com 返回 NULL。
    猜你喜欢
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2012-06-22
    • 2014-11-22
    • 2021-12-30
    相关资源
    最近更新 更多