Tuesday, 6 October 2015

How can I read request-headers in PHP


$headers = apache_request_headers();
print_r($headers);

Following are the Response of apache_request_headers()
How can I read request-headers in PHP?



Question: What is apache_request_headers()?
This function fetch all HTTP request headers.


Question: What format it return when success?
An associative array of all the HTTP headers in the current request.


Question: What happen when request failed?
It return FALSE when failed.


Question: Is it availble in all PHP Version?
No, It works only with >= PHP 5.4.


Question: How can I get header values less than 5.4 version
function getRequestHeadersCustomFunction() {
    $headers = array();
    foreach($_SERVER as $key => $value) {
        if (substr($key, 0, 5) <> 'HTTP_') {
            continue;
        }
        $headerKey = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
        $headers[$headerKey] = $value;
    }
    return $headers;
}
print_r(getRequestHeadersCustomFunction());