http_parse_headers
Returns an array on success or FALSE on failure.
Examples
Example #1 Using http_parse_headers()
$headers = «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 ( http_parse_headers ( $headers ));
?>?php
The above example will output:
Array ( [Content-Type] => text/html; charset=UTF-8 [Server] => Funky/1.0 [Set-Cookie] => Array ( [0] => foo=bar [1] => baz=quux ) [Folded] => works too )
See Also
User Contributed Notes 7 notes
The line
$headers [ 0 ] = trim ( $h [ 0 ]); trim ( $h [ 0 ]);
?>
Should be changed to:
$headers [ 0 ] = trim ( $h [ 0 ]);
?>
Taken from http://www.php.net/manual/en/function.http-parse-headers.php#112917 and modified to: make folded work too, return status in first key.
if (! function_exists ( ‘http_parse_headers’ ))
function http_parse_headers ( $raw_headers )
$headers = array();
$key = » ; // [+]
foreach( explode ( «\n» , $raw_headers ) as $i => $h )
$h = explode ( ‘:’ , $h , 2 );
if (isset( $h [ 1 ]))
if (!isset( $headers [ $h [ 0 ]]))
$headers [ $h [ 0 ]] = trim ( $h [ 1 ]);
elseif ( is_array ( $headers [ $h [ 0 ]]))
// $tmp = array_merge($headers[$h[0]], array(trim($h[1]))); // [-]
// $headers[$h[0]] = $tmp; // [-]
$headers [ $h [ 0 ]] = array_merge ( $headers [ $h [ 0 ]], array( trim ( $h [ 1 ]))); // [+]
>
else
// $tmp = array_merge(array($headers[$h[0]]), array(trim($h[1]))); // [-]
// $headers[$h[0]] = $tmp; // [-]
$headers [ $h [ 0 ]] = array_merge (array( $headers [ $h [ 0 ]]), array( trim ( $h [ 1 ]))); // [+]
>
$key = $h [ 0 ]; // [+]
>
else // [+]
< // [+]if ( substr ( $h [ 0 ], 0 , 1 ) == «\t» ) // [+]
$headers [ $key ] .= «\r\n\t» . trim ( $h [ 0 ]); // [+]
elseif (! $key ) // [+]
$headers [ 0 ] = trim ( $h [ 0 ]); trim ( $h [ 0 ]); // [+]
> // [+]
>
$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 ( http_parse_headers ( $headers ));
?>
The above example will output:
Array
(
[0] => HTTP/1.1 200 OK
[content-type] => text/html; charset=UTF-8
[Server] => Funky/1.0
[Set-Cookie] => Array
(
[0] => foo=bar
[1] => baz=quux
)
if (!function_exists(‘http_parse_headers’)) <
function http_parse_headers ($raw_headers) <
$headers = array(); // $headers = [];
foreach (explode(«\n», $raw_headers) as $i => $h) $h = explode(‘:’, $h, 2);
if (isset($h[1])) if(!isset($headers[$h[0]])) $headers[$h[0]] = trim($h[1]);
> else if(is_array($headers[$h[0]])) $tmp = array_merge($headers[$h[0]],array(trim($h[1])));
$headers[$h[0]] = $tmp;
> else $tmp = array_merge(array($headers[$h[0]]),array(trim($h[1])));
$headers[$h[0]] = $tmp;
>
>
>
$headers = «HTTP/1.1 302 Found
Server: nginx
Date: Sat, 27 Apr 2013 08:07:57 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 976
Connection: keep-alive
X-Frame-Options: sameorigin
X-Runtime: 443
Status: 302
Cache-Control: max-age=86400
Expires: Sun, 28 Apr 2013 08:07:56 GMT
Vary: Accept-Encoding,User-Agent
Strict-Transport-Security: max-age=3600 ; includeSubDomains» ;
if (! function_exists ( ‘http_parse_headers’ )) function http_parse_headers ( $raw_headers ) $headers = [];
foreach ( explode ( «\n» , $raw_headers ) as $i => $h ) $h = explode ( ‘:’ , $h , 2 );
if (isset( $h [ 1 ])) $headers [ $h [ 0 ]] = trim ( $h [ 1 ]);
>
>
var_dump ( http_parse_headers ( $headers ));
?>
array(12) [«Server»]=>
string(5) «nginx»
[«Date»]=>
string(29) «Sat, 27 Apr 2013 08:07:57 GMT»
[«Content-Type»]=>
string(24) «text/html; charset=utf-8»
[«Content-Length»]=>
string(3) «976»
[«Connection»]=>
string(10) «keep-alive»
[«X-Frame-Options»]=>
string(10) «sameorigin»
[«X-Runtime»]=>
string(3) «443»
[«Status»]=>
string(3) «302»
[«Cache-Control»]=>
string(13) «max-age=86400»
[«Expires»]=>
string(29) «Sun, 28 Apr 2013 08:07:56 GMT»
[«Vary»]=>
string(26) «Accept-Encoding,User-Agent»
[«Strict-Transport-Security»]=>
string(32) «max-age=3600 ; includeSubDomains»
>
$headers = «content-type: text/html; charset=UTF-8\r\n» .
«Server: Nginx\r\n» .
«set-cookie: user=\r\n\tunknown\r\n» .
«set-cookie: pass=strong\r\n\tpassword\r\n» .
«Set-Cookie: > .
«HOST:github.com» ;
function http_parse_headers ( $raw )
$k = » ;
$out = [];
foreach ( $exp as $v ) $exp = explode ( ‘:’ , $v , 2 );
if (isset( $exp [ 1 ])) /** Сonvert to ‘Word-Word’ */
$k = strtolower ( $exp [ 0 ]);
$k = preg_replace_callback ( ‘/\b[a-z]/’ , function ( $m ) < return strtoupper ( $m [ 0 ]); >, $k );
if (!isset( $out [ $k ])) $out [ $k ] = []; /** for in_array */
if (! in_array ( $value , $out [ $k ])) $out [ $k ][] = $value ; /** New element in array */
> else $value = trim ( $exp [ 0 ]);
$out [ $k ][ $i ] .= «\r\n\t» . $value ;
> elseif (! $k )
$out [ 0 ] = $value ;
>
>
/** Array has only once element — convert in string */
$out = array_map (function ( $v ) < return count ( $v ) < 2 ? $v [ 0 ] : $v ; >, $out );
return $out ;
>
?>
Old function output with error
array ( size = 5 )
‘content-type’ => string ‘text/html; charset=UTF-8’ ( length = 24 )
‘Server’ => string ‘Nginx’ ( length = 5 )
‘set-cookie’ => string ‘Array // Notice: Array to string conversion
password’ ( length = 16 )
‘Set-Cookie’ => string ‘id=1’ ( length = 4 )
‘HOST’ => string ‘github.com’ ( length = 10 )
?>
My function output
array ( size = 4 )
‘Content-Type’ => string ‘text/html; charset=UTF-8’ ( length = 24 )
‘Server’ => string ‘Nginx’ ( length = 5 )
‘Set-Cookie’ =>
array ( size = 3 )
0 => string ‘user=
unknown’ ( length = 15 )
1 => string ‘pass=strong
password’ ( length = 22 )
2 => string ‘id=1’ ( length = 4 )
‘Host’ => string ‘github.com’ ( length = 10 )
?>
If you don’t have access to the PECL library, you can use this code to parse headers contained in strings.
Note that it’s probably not as robust as the PECL version, as it only parses if the headers are separated by newlines (\n). This isn’t a problem in most cases, though, as the standard suggests to use \r\n as the delimiter for headers.
HTTP response code is put into ‘status’.
function http_parse_headers ( $headers = false ) if( $headers === false ) return false ;
>
$headers = str_replace ( «\r» , «» , $headers );
$headers = explode ( «\n» , $headers );
foreach( $headers as $value ) $header = explode ( «: » , $value );
if( $header [ 0 ] && ! $header [ 1 ]) $headerdata [ ‘status’ ] = $header [ 0 ];
>
elseif( $header [ 0 ] && $header [ 1 ]) $headerdata [ $header [ 0 ]] = $header [ 1 ];
>
>
return $headerdata ;
>
$headers = «HTTP/1.1 200 OK\r\n
Date: Tue, 08 Aug 2006 05:32:01 GMT\r\n
X-Powered-By: PHP/4.4.3-dev\r\n
Data 1: Value for Data 1\r\n
Data 2: Value for Data 2\r\n
Connection: close\r\n
Content-Type: text/html\r\n» ;
array( 7 ) [ «status» ]=>
string ( 15 ) «HTTP/1.1 200 OK»
[ «Date» ]=>
string ( 29 ) «Tue, 08 Aug 2006 05:32:01 GMT»
[ «X-Powered-By» ]=>
string ( 13 ) «PHP/4.4.3-dev»
[ «Data 1» ]=>
string ( 16 ) «Value for Data 1»
[ «Data 2» ]=>
string ( 16 ) «Value for Data 2»
[ «Connection» ]=>
string ( 5 ) «close»
[ «Content-Type» ]=>
string ( 9 ) «text/html»
>
?>
This one works even better:
function http_parse_headers ( $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 ;
>
- HTTP Functions
- http_cache_etag
- http_cache_last_modified
- http_chunked_decode
- http_deflate
- http_inflate
- http_build_cookie
- http_date
- http_get_request_body_stream
- http_get_request_body
- http_get_request_headers
- http_match_etag
- http_match_modified
- http_match_request_header
- http_support
- http_negotiate_charset
- http_negotiate_content_type
- http_negotiate_language
- ob_deflatehandler
- ob_etaghandler
- ob_inflatehandler
- http_parse_cookie
- http_parse_headers
- http_parse_message
- http_parse_params
- http_persistent_handles_clean
- http_persistent_handles_count
- http_persistent_handles_ident
- http_get
- http_head
- http_post_data
- http_post_fields
- http_put_data
- http_put_file
- http_put_stream
- http_request_body_encode
- http_request_method_exists
- http_request_method_name
- http_request_method_register
- http_request_method_unregister
- http_request
- http_redirect
- http_send_content_disposition
- http_send_content_type
- http_send_data
- http_send_file
- http_send_last_modified
- http_send_status
- http_send_stream
- http_throttle
- http_build_str
- http_build_url
gonejack / $http_response_header_parser.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
/** * Parse a set of HTTP headers * * @param array The php headers to be parsed * @param [string] The name of the header to be retrieved * @return A header value if a header is passed; * An array with all the headers otherwise */ function parseHeaders ( array $ headers , $ header = null ) $ output = array (); if ( ‘HTTP’ === substr( $ headers [ 0 ], 0 , 4 )) list (, $ output [ ‘status’ ], $ output [ ‘status_text’ ]) = explode( ‘ ‘ , $ headers [ 0 ]); unset( $ headers [ 0 ]); > foreach ( $ headers as $ v ) $ h = preg_split( ‘/:\s*/’ , $ v ); $ output [strtolower( $ h [ 0 ])] = $ h [ 1 ]; > if ( null !== $ header ) if (isset( $ output [strtolower( $ header )])) return $ output [strtolower( $ header )]; > return ; > return $ output ; > 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
$http_response_header is a Array like Array ( [0] => HTTP/1.1 200 OK [1] => Date: Thu, 14 Oct 2010 09:46:18 GMT [2] => Server: Apache/2.2 [3] => Last-Modified: Sat, 07 Feb 2009 16:31:04 GMT [4] => ETag: «340011c-3614-46256a9e66200» [5] => Accept-Ranges: bytes [6] => Content-Length: 13844 [7] => Vary: User-Agent [8] => Expires: Thu, 15 Apr 2020 20:00:00 GMT [9] => Connection: close [10] => Content-Type: image/png ) which is useful when you what to know the situation being after using the file_get_contents(), but it’s not that easy to get the status code or status text since it’s a wrap of HTTP headers, so here’s a parser(from internet) to make it more easy to get specific header. How to parse response headers in PHP?
When working with APIs or HTTP requests in PHP, it’s common to need to read and parse the headers returned in the response. In this guide, we’ll cover how to parse response headers in PHP using the built-in function headers_list().
Using headers_list()
The headers_list() function returns an array of all the headers sent by the server. To parse them, we can loop through the array using the foreach() loop and explode() function to separate the header name from its value. Here’s an example:
$response_headers = headers_list(); foreach ($response_headers as $header) < $header_parts = explode(':', $header, 2); $header_name = trim($header_parts[0]); $header_value = trim($header_parts[1]); // Do something with the header name and value >
In this example, we first call headers_list() to get an array of all the headers. Then, we loop through each header using foreach() and use explode() to split the header into its name and value parts. We trim() each part to remove any leading or trailing whitespace. Finally, we can use the header name and value as needed.
Example
Here’s an example of how we might use this technique to extract the content-type header from an HTTP response:
// Make an HTTP request $response = file_get_contents('https://www.example.com'); // Get the response headers $response_headers = headers_list(); // Find the content-type header $content_type = null; foreach ($response_headers as $header) < $header_parts = explode(':', $header, 2); $header_name = trim($header_parts[0]); $header_value = trim($header_parts[1]); if ($header_name === 'Content-Type') < $content_type = $header_value; break; >> // Print the content-type header echo "Content-Type: $content_type\n";
In this example, we use file_get_contents() to make an HTTP request to the example.com website. We then call headers_list() to get an array of all the headers returned in the response. We loop through each header and check if its name is ‘Content-Type’. If we find the content-type header, we store its value in the $content_type variable and exit the loop. Finally, we print the content-type header to the console.
Conclusion
Parsing response headers in PHP is a common task when working with APIs or HTTP requests. By using the headers_list() function and a simple loop, we can easily extract the headers we need from an HTTP response.