PHP Snippet – Parse HTTP Headers String Into An Associative Array

Here Is A POST Request Header String (without the data-body)

POST /collect HTTP/1.1
Connection: keep-alive
Cache-Control: no-cache
Accept: image/webp,*/*;q=0.8
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Referer: http://localhost/a/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en,en-US;q=0.8,he;q=0.6
Cookie: _ga=GA1.2.53d1ee9b3c4810.54724696
Content-type: application/x-www-form-urlencoded
Content-Length: 485

without the usage of external modules, lets parse it into associative array, with fallback for lines like POST /collect HTTP/1.1 which do not have to be with string-key, for those, we will use the index of the line (starting from 0).

essentially exactly the same look&feel, you’ll get from $responseHeaders = get_headers($url, true);, but for any given string,
for example you can specify using CURL’s CURLINFO_HEADER_OUT => true to track the handle’s request string, so later you will use $info = curl_getinfo($ch) followed by $requestHeaders = $info['request_header'] to get the string (or simply use curl_getinfo($ch, CURLINFO_HEADER_OUT) to get the string)

//-------------------------------------------------------------------------------- process request headers from info, from string to associative array
$requestHeaders = call_user_func_array(function ($info) {
  $headersAssociative = array();

  $headers = (isset($info['request_header']) === true) ? $info['request_header'] : '';
  $headers = explode("\r\n", $headers);

  foreach ($headers as $i => $headerLine) {
    if($headerLine === ''){ //skip empty lines.

    $parts = explode(': ', $headerLine);
    if (isset($parts[1])) {
      $headersAssociative[ $parts[0] ] = $parts[1]; //use key name
    } else {
      $headersAssociative[ $i ] = $headerLine; //use index as key name
  return $headersAssociative;

}, array($info)); //pass the $info as parameter to call_user_func_array

which will be resolved to following var_dump

array (size=14)
  0 => string 'POST /collect HTTP/1.1' (length=22)
  'Host' => string '' (length=23)
  'Connection' => string 'keep-alive' (length=10)
  'Cache-Control' => string 'no-cache' (length=8)
  'Accept' => string 'image/webp,*/*;q=0.8' (length=20)
  'Pragma' => string 'no-cache' (length=8)
  'User-Agent' => string 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36' (length=109)
  'Referer' => string 'http://localhost/a/' (length=19)
  'Accept-Encoding' => string 'gzip,deflate,sdch' (length=17)
  'Accept-Language' => string 'en,en-US;q=0.8,he;q=0.6' (length=23)
  'Cookie' => string '_ga=GA1.2.53d1ee9b3c4880.54724696' (length=33)
  'X-Forward-For' => string '' (length=7)
  'Content-type' => string 'application/x-www-form-urlencoded' (length=33)
  'Content-Length' => string '485' (length=3)