繁体   English   中英

页面可通过file_get_contents读取,但不能通过cURL读取

[英]Page readable by file_get_contents but not cURL

我正在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标头,但这没什么区别。

添加的答案供参考:

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

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

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

也许您的服务器已禁用cURL,请尝试使用function_exists进行检查:

var_dump(function_exists('curl_version'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM