Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yookoala
Created August 29, 2018 04:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yookoala/017f056c34a169514fbf0cd7cc5b2e78 to your computer and use it in GitHub Desktop.
Save yookoala/017f056c34a169514fbf0cd7cc5b2e78 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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