- preg_match: documentation ( source)
- print_r: documentation ( source)
- explode: documentation ( source)
- trim: documentation ( source)
- preg_replace: documentation ( source)
- strtolower: documentation ( source)
<?php
function parseHeaders( $header )
{
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if( isset($retVal[$match[1]]) ) {
if (!is_array($retVal[$match[1]])) {
$retVal[$match[1]] = array($retVal[$match[1]]);
}
$retVal[$match[1]][] = $match[2];
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
return $retVal;
}
$headers = "HTTP/1.1 200 OK\r\n".
"content-type: text/html; charset=UTF-8\r\n".
"Server: Funky/1.0\r\n".
"Set-Cookie: foo=bar\r\n".
"Set-Cookie: baz=quux\r\n".
"Folded: works\r\n\ttoo\r\n";
print_r(parseHeaders($headers));