How to parse http response header in PHP

When we send a http request header to web server, it will give us a response header. We need to parse this response header to get some information on what we need, such as cookie, content length or last modified time etc.

How to parse http response header using php

Here is an example code for parsing response hearder.

<?php
$response = 'HTTP/1.1 200 OK
Date: Thu, 23 Aug 2018 06:05:04 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.3.10-1ubuntu3.25
Set-Cookie: AIBOOK_Download_ID=TlRBMU9EUndaR1k9; expires=Thu, 23-Aug-2018 07:05:04 GMT; path=/
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 2840
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html';

function parse_http_header($header){
$headers = explode("\n",$header);
//print_r($headers);
$arr = array();
foreach ($headers as $key => $r) {
// Match the header name up to ':', compare lower case
if (stripos($r, ':') >0) {
list($headername, $headervalue) = explode(":", $r, 2);
$arr[trim($headername)] = trim($headervalue);
}
}
return $arr;
}

print_r(parse_http_header($response));
?>

And the output is:

Array
(
[Date] => Thu, 23 Aug 2018 06:05:04 GMT
[Server] => Apache/2.2.22 (Ubuntu)
[X-Powered-By] => PHP/5.3.10-1ubuntu3.25
[Set-Cookie] => AIBOOK_Download_ID=TlRBMU9EUndaR1k9; expires=Thu, 23-Aug-2018 07:05:04 GMT; path=/
[Vary] => Accept-Encoding
[Content-Encoding] => gzip
[Content-Length] => 2840
[Keep-Alive] => timeout=5, max=100
[Connection] => Keep-Alive
[Content-Type] => text/html
)

 

,