Skip to content

Instantly share code, notes, and snippets.

@gonejack
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gonejack/bb79efeaa12966610f2d to your computer and use it in GitHub Desktop.
Save gonejack/bb79efeaa12966610f2d to your computer and use it in GitHub Desktop.
parse $http_response_header
<?php
/**
* Parse a set of HTTP headers
*
* @param array The php headers to be parsed
* @param [string] The name of the header to be retrieved
* @return A header value if a header is passed;
* An array with all the headers otherwise
*/
function parseHeaders(array $headers, $header = null) {
$output = array();
if ('HTTP' === substr($headers[0], 0, 4)) {
list(, $output['status'], $output['status_text']) = explode(' ', $headers[0]);
unset($headers[0]);
}
foreach ($headers as $v) {
$h = preg_split('/:\s*/', $v);
$output[strtolower($h[0])] = $h[1];
}
if (null !== $header) {
if (isset($output[strtolower($header)])) {
return $output[strtolower($header)];
}
return;
}
return $output;
}
$http_response_header is a Array like
Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Thu, 14 Oct 2010 09:46:18 GMT
[2] => Server: Apache/2.2
[3] => Last-Modified: Sat, 07 Feb 2009 16:31:04 GMT
[4] => ETag: "340011c-3614-46256a9e66200"
[5] => Accept-Ranges: bytes
[6] => Content-Length: 13844
[7] => Vary: User-Agent
[8] => Expires: Thu, 15 Apr 2020 20:00:00 GMT
[9] => Connection: close
[10] => Content-Type: image/png
)
which is useful when you what to know the situation being after using the file_get_contents(), but it's not that easy to get the status code or status text since it's a wrap of HTTP headers, so here's a parser(from internet) to make it more easy to get specific header.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment