Last active
October 29, 2021 16:32
-
-
Save WinterSilence/66f8d00bc1fe8018e4ea856df5859987 to your computer and use it in GitHub Desktop.
Polyfill for PHP function getallheaders() (alias apache_request_headers())
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!\function_exists('getallheaders')) { | |
/** | |
* Returns HTTP headers for the server request. | |
* | |
* @return string[] The HTTP headers | |
*/ | |
function getallheaders() | |
{ | |
/** @var string[]|null $headers */ | |
static $headers; | |
if (!isset($headers)) { | |
$headers = []; | |
$extraHeaders = [ | |
'CONTENT_TYPE' => 'Content-Type', | |
'CONTENT_LENGTH' => 'Content-Length', | |
'CONTENT_MD5' => 'Content-MD5', | |
'PHP_AUTH_DIGEST' => 'Authorization', | |
]; | |
/** @var array $server */ | |
$server = \filter_input_array(\INPUT_SERVER, \FILTER_SANITIZE_STRING); | |
foreach ($server as $key => $value) { | |
if (isset($extraHeaders[$key])) { | |
$headers[$extraHeaders[$key]] = $value; | |
} elseif (\strncmp($key, 'HTTP_', 5) === 0) { | |
$key = \strtr(\substr($key, 5), ['_' => '-']); | |
$key = \ucwords(\strtolower($key), '-'); | |
$headers[$key] = $value; | |
} | |
} | |
if ( | |
!isset($headers['Authorization']) | |
&& (isset($server['AUTH_TYPE']) || isset($server['PHP_AUTH_USER'])) | |
) { | |
$headers['Authorization'] = isset($server['AUTH_TYPE']) ? $server['AUTH_TYPE'] : 'Basic'; | |
if (isset($server['PHP_AUTH_USER'])) { | |
$token = $server['PHP_AUTH_USER'] . ':' . (isset($server['PHP_AUTH_PW']) ? $server['PHP_AUTH_PW'] : ''); | |
$headers['Authorization'] .= ' ' . \base64_encode($token); | |
} | |
} | |
} | |
return $headers; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment