Skip to content

Instantly share code, notes, and snippets.

@kopiro
Last active April 24, 2020 18:27
Show Gist options
  • Save kopiro/8453927c9232939d4ba326115ad5647d to your computer and use it in GitHub Desktop.
Save kopiro/8453927c9232939d4ba326115ad5647d to your computer and use it in GitHub Desktop.
Parse headers in PHP
<?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;
}
@dolmen
Copy link

dolmen commented Jan 15, 2018

This code doesn't handle the case of multiple header lines. For example, multiple Set-Cookie lines.

@lastguest
Copy link

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