In the PHP documentation you can find http_parse_headers, which requires the PECL HTTP module.

If you can’t install the PECL module you can find some alternatives to replace it in the comments within PHP documentation. I took one left by an Anonymous coder, fixed some bugs it had and extend it to also return parsed Request and Status Lines using the field names defined under RFC2616.

Hope you find it useful, since I’m really creative with names I called this baby http_parse_headers2, pretty original huh?

/**
 * Parses HTTP headers and request/status lines into an associative array.
 *
 * @author  Anonymous
 * @author  Aldo Fregoso C.

 * @license Public Domain
 *
 * @param string $header string containing HTTP headers.
 *
 * @return array Parsed headers with request/status lines using RFC2616's field names.
 */
function http_parse_headers2( $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] ) ) );
            $match[2] = trim( $match[2] );

            if ( isset($retVal[$match[1]]) )
            {
                if ( is_array( $retVal[$match[1]] ) )
                {
                    $retVal[$match[1]][] = $match[2];
                }
                else
                {
                    $retVal[$match[1]] = array ( $retVal[$match[1]], $match[2] );
                }
            }
            else
            {
                $retVal[$match[1]] = $match[2];
            }
        }
        else if ( preg_match( '/([A-Za-z]+) (.*) HTTP\/([\d.]+)/', $field, $match ) )
        {
            $retVal["Request-Line"] = array (
                "Method"       => $match[1],
                "Request-URI"  => $match[2],
                "HTTP-Version" => $match[3]
            );
        }
        else if ( preg_match( '/HTTP\/([\d.]+) (\d+) (.*)/', $field, $match ) )
        {
            $retVal["Status-Line"] = array (
                "HTTP-Version"  => $match[1],
                "Status-Code"   => $match[2],
                "Reason-Phrase" => $match[3]
            );
        }
    }
    return $retVal;
}
© 2011 Aldo.MX Suffusion theme by Sayontan Sinha