百科狗-知识改变命运!
--

get_headers() - php 网址URL函数

是丫丫呀1年前 (2023-11-21)阅读数 21#技术干货
文章标签数组

get_headers()

(PHP 5, PHP 7)

get_headers() - php 网址URL函数

取得服务器响应一个 HTTP 请求所发送的所有标头

说明

get_headers(string $url[,int $format= 0]): array

get_headers()返回一个数组,包含有服务器响应一个 HTTP 请求所发送的标头。

参数

$url

目标 URL。

$format

如果将可选的$format参数设为 1,则get_headers()会解析相应的信息并设定数组的键名。

返回值

返回包含有服务器响应一个 HTTP 请求所发送标头的索引或关联数组,如果失败则返回FALSE

更新日志

版本说明
5.1.3自 PHP 5.1.3 起本函数使用默认的流上下文,其可以用stream_context_get_default()函数设定和修改。

范例

Example #1get_headers()例子

以上例程的输出类似于:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)
Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

Example #2get_headers()using HEAD example

参见

  • apache_request_headers() 获取全部 HTTP 请求头信息
Seems like there are some people who are looking for only the 3-digit HTTP response code - here is a quick and nasty solution:

How easy is that? Echo the function containing the URL you want to check the response code for, and voilà. Custom redirects, alternative for blocked is_file() or flie_exists() functions (like I seem to have on my servers) hence the cheap workaround. But hey - it works!
Pudding
How to check if a url points to a valid video 
To check URL validity, this has been working nicely for me:
function url_valid(&$url) {
 $file_headers = @get_headers($url);
 if ($file_headers === false) return false; // when server not found
 foreach($file_headers as $header) { // parse all headers:
  // corrects $url when 301/302 redirect(s) lead(s) to 200:
  if(preg_match("/^Location: (http.+)$/",$header,$m)) $url=$m[1]; 
  // grabs the last $header $code, in case of redirect(s):
  if(preg_match("/^HTTP.+\s(\d\d\d)\s/",$header,$m)) $code=$m[1]; 
 } // End foreach...
 if($code==200) return true; // $code 200 == all OK
 else return false; // All else has failed, so this must be a bad link
} // End function url_exists
I know you're not supposed to reference other notes, but sincere props to Nick at Innovaweb's comment, for which I base this addition to his idea:
If you use that function, it will return a string, which is great if you are checking for only files that return 404, or 200, or whatnot. If you cast the string value to an integer, you can perform mathematical comparison on it. 
For example:

Rule of thumb is if the response is less than 400, then the file's there, even if it doesn't return 200.
Note that get_headers should not be used against a URL that was gathered via user input. The timeout option in the stream context only affects the idle time between data in the stream. It does not affect connection time or the overall time of the request. 
(Unfortunately, this is not mentioned in the docs for the timeout option, but has been discussed in a number of code discussions elsewhere, and I have done my own tests to confirm the conclusions of those discussions.)
Thus it is very easy for a user to give you a URL that acts like a Slowloris attack - feeding your get_headers function 1 header only often enough to avoid the stream timeout.
If you are publishing your code, even default_socket_timeout cannot be relied on to remedy this, because it is broken for the HTTPS protocol on many but the more recent versions of PHP: https://bugs.php.net/bug.php?id=41631
With get_headers accepting user input, it can be very easy for an attacker to make all of your PHP child processes become busy.
Instead, use cURL functions to get headers for a URL provided by the user and parse those headers manually, as CURLOPT_TIMEOUT applies to the entire request.
If you want to get headers that current PHP process is going to send back to browser, see headers_list()
If the URL redirected and the new target is also redirected, we got the Locations in array. Also we got the HTTP codes in a number indexed values. 
Here a PART of the header (not all), how it is look like with this redirection chain ( the id=4 is the landing page):
/test.php?id=1 -> /test.php?id=2 -> /test.php?id=3 -> /test.php?id=4
array 
(
  [0] => HTTP/1.1 302 Moved Temporarily
  [Location] => Array
    (
      [0] => /test.php?id=2
      [1] => /test.php?id=3
      [2] => /test.php?id=4
    )
  [1] => HTTP/1.1 302 Moved Temporarily
  [2] => HTTP/1.1 302 Moved Temporarily
  [3] => HTTP/1.1 200 OK
)
In a typical situation we need only the landing page information, so here is a small code to get it:
$result = array();
$header = get_headers($url, 1);
foreach ($header as $key=>$value) {
  if (is_array($value)) {
    $value = end($value);
  }
  $result[$key] = $value;
}
Note that get_headers **WILL follow redirections** (HTTP redirections). New headers will be appended to the array if $format=0. If $format=1 each redundant header will be an array of multiple values, one for each redirection.
For example: 
@Jim Greene:
if the URL does not exist, it returns incomplete headers, making the substring default to rubbish.
The integer value of rubbish is always 0. So your lower than 400 does not always means it exists!
If you don't want to display Warning when get_headers() function fails, you can simply add at-sign (@) before it. 
hey, i came across this afew weeks ago and used the function in an app for recording info about domains that my company owns, and found that the status this returns was wrong most of the time (400 bad request or void for sites that were clearly online). then looking into it i noticed the problem was that it wasn't able to get the correct info about sites with redirections. but thats not the full problem because everything on my server was returning the wrong status too. i searched around on php.net for other info and found that fsockopen's example worked better and only needed some tweeking.
heres the function i put together from it and a small change.

this returns an array of the header (only problem being that if the site doesn't have correct html it'll pull in some content too).
hope this'll help someone else.
It should be noted that rather than returning "false" on failure, this function (and others) return a big phat WARNING that will halt your script in its tracks if you do not have error reporting /warning turned off.
Thats just insane! Any function that does something like fetch a URL should simply return false, without a warning, if the URL fails for whatever reason other than it is badly formatted.
The following code dose NOT work with PHP version 7.0.26 with my server.
Some other setting may be required?
Tried with website pages and path to local files.
The word 'Finished' is printed only. 
The function will handle up to five redirects.
Enjoy!
I've noticed it.
Some Server will simply return the false reply header if you sent 'HEAD' request instead of 'GET'. The 'GET' request header always receiving the most actual HTTP header instead of 'HEAD' request header. But If you don't mind for a fast but risky method then 'HEAD' request is better for you.
btw ... this is get header with additional information such as User, Pass & Refferer. ... 

Regards.
Donovan
aeontech, this the below change adds support for SSL connections. Thanks for the code!
    if (isset($url_info['scheme']) && $url_info['scheme'] == 'https') {
      $port = 443;
      $fp=fsockopen('ssl://'.$url_info['host'], $port, $errno, $errstr, 30);
    } else {
      $port = isset($url_info['port']) ? $url_info['port'] : 80;
      $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
    }
Should be the same than the original get_headers(): 
For anyone reading the previous comments, here is code that takes into account all the previous suggestions and includes a bugfix, too.
This code basically provides the "get_headers" function even on systems that are not running PHP 5.0. It uses strtolower() on the keys, as suggested. It uses the $h2 array instead of the $key, as suggested. It removes a line about unsetting the $key -- no reason to unset something which is no longer used. And I've changed the status header to be named "status" (instead of "0") in the array. Note that if more than one header is returned without a label, they'll be stuck in "status" -- but I think status is the only header that comes back without a label, so it works for me. So, first the code, then a sample of the usage: 
In some cases, you don't want get_headers to follow redirects. For example, some of my servers can access a particular website, which sends a redirect header. The site it is redirected to, however, has me firewalled. I need to take the 302 redirected url, and do something to it to give me a new url that I *can* connect to.
The following will give you output similar to get_headers, except it has a timeout, and it doesn't follow redirects: 
I found that this function is the slowest in obtaining the headers of a page probably because it uses a GET request rather then a HEAD request. Over 10,000,000 trials of obtaining the headers of a page from a server i found the following (results in seconds).
cURL: Mean: 0.584127946. Sigma: 0.050581736.
fsocketopen: Mean: 0.622114251. Sigma: 0.263170424.
get_headers: Mean: 0.90375551. Sigma: 0.273823419.
cURL was the fastest with fsocketopens being the second fastest. I noticed as well that fsocketopen had some outliers where as cURL did not.
Unfortunately there is still no useful output format to handle redirects.
This function will bring all non-broken headers into a usable format. Too bad it has to call the get_headers() funtion 2 times, but i dont see any other possibility right now. 
Testing the validity of a URL that is preceded by one or more server redirects is tricky. There will be more than one status code returned and all but the first will be redirect codes.
This function will return an integer containing the three digit status code of the last code returned, which is what you want.
  function getStatus($url) {
    $headers = @get_headers($url, true);
    $value = NULL;
    if ($headers === false) {
      return $headers;
    }
    foreach ($headers as $k => $v) {
      if (!is_int($k)) {
        continue;
      }
      $value = $v;
    }
    return (int) substr($value, strpos($value, ' ', 8) + 1, 3);
   }
If getHeaders() fails, PHP will throw an error. Test the return value for === false.
Content-Type returns a value depending only on the extension and not the real MIME TYPE. 
So, bad_file.exe renamed to good_file.doc will return application/msword
A file without extension returns a 404.
In response to dotpointer's modification of Jamaz' solution...
Here is a small modification of your function, this adds the emulation of the optional $format parameter.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)