23 Sep 2013

Get a header field [PHP]

I'm surprised PHP has getallheaders() and headers_list to retrieve ALL headers but no function for retrieving a single header.

Here is a quick one using headers_list()

1
2
3
4
5
6
7
8
9
10
<?php
// echo get_header('X-HTTP-Method-Override');
function get_header($field) {
    $headers = headers_list();
    foreach ($headers as $header) {
        list($key, $value) = preg_split('/:\s*/', $header);
        if ($key == $field)
            return $value;
    }
}

My name is Opeyemi Obembe. I build things for web and mobile. You should follow me on Twitter (@kehers).