As suggested in the other answer here, I have used the function from the comments in the PHP documentation, but found that it's suboptimal, hard to read/maintain, and not complete compared to the (non-conforming) casing of some headers.
So because I needed to really be able to rely on it, I recoded it to be more obvious and handle more edge-cases better as well – the original code even states "do some nasty string manipulations to restore the original letter case" and "this should work in most cases", which doesn't sound nice for something you should be able to depend on.
It's not perfect, but I find that it's more reliable. One thing it lacks is to work on the actual or original headers, as any modifications to $_SERVER
will be reflected in the output. This can be mitigated by making the result static and running the function as the first thing on every request.
<?php
// Drop-in replacement for apache_request_headers() when it's not available
if(!function_exists('apache_request_headers')) {
function apache_request_headers() {
// Based on: http://www.iana.org/assignments/message-headers/message-headers.xml#perm-headers
$arrCasedHeaders = array(
// HTTP
'Dasl' => 'DASL',
'Dav' => 'DAV',
'Etag' => 'ETag',
'Mime-Version' => 'MIME-Version',
'Slug' => 'SLUG',
'Te' => 'TE',
'Www-Authenticate' => 'WWW-Authenticate',
// MIME
'Content-Md5' => 'Content-MD5',
'Content-Id' => 'Content-ID',
'Content-Features' => 'Content-features',
);
$arrHttpHeaders = array();
foreach($_SERVER as $strKey => $mixValue) {
if('HTTP_' !== substr($strKey, 0, 5)) {
continue;
}
$strHeaderKey = strtolower(substr($strKey, 5));
if(0 < substr_count($strHeaderKey, '_')) {
$arrHeaderKey = explode('_', $strHeaderKey);
$arrHeaderKey = array_map('ucfirst', $arrHeaderKey);
$strHeaderKey = implode('-', $arrHeaderKey);
}
else {
$strHeaderKey = ucfirst($strHeaderKey);
}
if(array_key_exists($strHeaderKey, $arrCasedHeaders)) {
$strHeaderKey = $arrCasedHeaders[$strHeaderKey];
}
$arrHttpHeaders[$strHeaderKey] = $mixValue;
}
return $arrHttpHeaders;
}
}