我正在使用
file_get_contents
与 API 进行交互,以执行简单的 GET
请求...但是有时它会抛出标头,表明存在错误。如何获取这些标头并确定是否存在问题?
Php 将在
file_get_contents
之后设置 $http_response_header ,其中包含响应标头作为标头行/字符串数组。如果您想要的只是标头响应,则没有必要使用curl(并且可能不应该,某些LAMP堆栈仍然没有cURL)。
$http_response_header 上的文档: http://php.net/manual/en/reserved.variables.httpresponseheader.php
示例:
file_get_contents('http://stacksocks.com');
foreach ($http_response_header as $header)
{
echo $header . "<br>\n";
}
来自评论帖子的提示:
1)该值随每个请求而变化 制作。
2) 当在方法/函数中使用时, 当前值必须传递给 方法/函数。使用 $http_response_header 直接在 未分配的方法/函数 函数/方法参数的值 将导致错误消息: 注意:未定义的变量: http_response_header
3) 数组长度和值 数组中的位置可能会改变 取决于被查询的服务器 以及收到的答复。我不是 确定是否有任何“绝对”值 数组中的位置。
4) $http_response_header 仅获取 使用 file_get_contents() 填充 当使用 URL 而不是本地文件时。 描述中说明了这一点 它提到了 HTTP_wrapper。
使用curl代替file_get_contents。
参见:http://www.php.net/manual/en/curl.examples-basic.php
我想如果您与 REST Api 通信,那么您实际上希望返回 Http 状态代码。在这种情况下,你可以这样做:
<?php
$ch = curl_init("http://www.example.com/api/users/1");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 501) {
echo 'Ops it not implemented';
}
fclose($fp);
?>
file_get_contents('http://example.com');
var_dump($http_response_header);