PHP无法从本地页面获取json,只有远程url
问题描述:
我目前正在使用Slim框架构建一个站点。我在我的网站上有一个端点设置,它正在工作,但是当试图使用PHP file_get_contents()
和json_decode()
得到它时,没有返回。当我运行相同的代码,但将url更改为远程公共API时,json将被解码并输出到页面。PHP无法从本地页面获取json,只有远程url
工作守则
$url = "https://jsonplaceholder.typicode.com/users";
$contents = file_get_contents($url);
$results = json_decode($contents); // Returns JSON array
不与当地现场工作
$url = "https://local/api/endpoint";
$contents = file_get_contents($url);
$results = json_decode($contents); // Returns NULL
上什么可能会导致此任何想法?可能是头文件?
答
您的本地端点失败,因为在您使用自签名证书的情况下,php无法验证SSL证书。在当地的发展,你可以绕过SSL CA通过修改默认的流上下文检查:
$stream_opts = [
"ssl" => [
"verify_peer"=>false,
"verify_peer_name"=>false,
]
];
$response = file_get_contents("https://local/api/endpoint",
false, stream_context_create($stream_opts));
当你把 - https://开头的本地/ API /端点到您的浏览器 - 你怎么看? – TimBrownlaw
'local/api/endpoint'给了我一个404,但是如果我通过HTTPS路由它,它给了我预期的json。 https可以做些什么,因为PHP只是发送http而不是? –
HTTPS从我的问题中的url文本中删除。在回答你的问题时,是的,那是需要检查的东西? – TimBrownlaw