Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parse the side effect variable $http_response_header of file_get_contents().
<?php
/**
* http_parse_response_header()
* Parse $http_response_header produced by file_get_contents().
*
* @param array $header
* Supposed $http_response_header or array alike.
* @param array
* Assoc array of the parsed version.
*/
function http_parse_response_header($header) {
if (empty($header)) return []; // return empty array
// parse status line
$status_line = array_shift($header);
if (!preg_match('/^(\w+)\/(\d+\.\d+) (\d+) (.+?)$/', $status_line, $matches))
throw new Exception("misformat status line: {$status_line}");
return [
'PROTOCOL' => $matches[1],
'PROTOCOL_VERSION' => $matches[2],
'STATUS_CODE' => $matches[3],
'STATUS' => $matches[4],
] + array_reduce($header, function ($carry, $line) {
// parse content line
list($key, $value) = explode(':', $line, 2);
if (!isset($carry[$key])) {
$carry[$key] = trim($value);
} else {
$carry[$key] .= "\n" . trim($value);
}
return $carry;
}, []);
}
@yookoala

This comment has been minimized.

Copy link
Owner Author

yookoala commented Aug 29, 2018

Example use:

<?php

$response = file_get_contents('https://foobar.com');
$response_header = http_parse_response_header($http_response_header);

if ($response_header['STATUS_CODE'] != '200') {
  echo "Error ({$response_header['STATUS_CODE']}): {$response_header['STATUS']}";
} else {
  echo $response;
}

?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.