PHP 获取没有 cURL 的 http 标头响应代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9724924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP get http header response code without cURL
提问by LeeTee
I have written a class that detects if cURL is available, if it is performs GET, POST, DELETE using cURL. In the cURL version I use curl_getinfo($curl, CURLINFO_HTTP_CODE);
to get the HTTP code. If is cURL is not available it uses fopen() to read the file contents. How do I get the HTTP header code without cURL?
我编写了一个类来检测 cURL 是否可用,如果它使用 cURL 执行 GET、POST、DELETE。在我curl_getinfo($curl, CURLINFO_HTTP_CODE);
用来获取 HTTP 代码的 cURL 版本中。如果 cURL 不可用,则使用 fopen() 读取文件内容。如何在没有 cURL 的情况下获取 HTTP 标头代码?
回答by Matt Beckman
Use get_headers:
使用get_headers:
<?php
$url = "http://www.example.com/";
$headers = get_headers($url);
$code = $headers[0];
?>
Edit:get_headers
requires an additional call, and is not appropriate for this scenario. Use $http_response_headers
as suggested by hakre.
编辑:get_headers
需要额外调用,不适合这种情况。$http_response_headers
按照hakre 的建议使用。
回答by hakre
Whenever you do some HTTP interaction, the special variable $http_response_header
on the same scope will contain all headers (incl. the status line header) that are resulted from the last HTTP interaction.
每当您进行一些 HTTP 交互时,$http_response_header
同一范围内的特殊变量将包含上次 HTTP 交互产生的所有标头(包括状态行标头)。
See here for an example how to parse it and obtain the status code.
有关如何解析它并获取状态代码的示例,请参见此处。