Last active
April 24, 2020 18:27
-
-
Save kopiro/8453927c9232939d4ba326115ad5647d to your computer and use it in GitHub Desktop.
Parse headers in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$headers = []; | |
foreach (explode("\r\n", substr($response, 0, strpos($response, "\r\n\r\n"))) as $i => $line) { | |
if ($i === 0) continue; | |
list ($key, $value) = explode(': ', $line); | |
$headers[$key] = $value; | |
} |
Added multi headers support and wrapped into a function :
function parse_headers($headers){
$results = [];
foreach (array_filter(explode("\r\n", trim($headers))) as $line) {
list ($key, $value) = explode(':', $line, 2);
$key = trim($key);
$value = trim($value);
if (isset($results[$key])) {
if (is_array($results[$key]))
$results[$key][] = $value;
else
$results[$key] = [$results[$key], $value];
} else {
$results[$key] = $value;
}
}
return $results;
}
The example code is now :
$headers = parse_headers(substr($response, 0, strpos($response, "\r\n\r\n")));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code doesn't handle the case of multiple header lines. For example, multiple
Set-Cookie
lines.