3 declare(strict_types=1);
5 namespace Laminas\Diactoros;
7 use function array_key_exists;
8 use function is_string;
9 use function str_starts_with;
10 use function strtolower;
15 * @param array $server Values obtained from the SAPI (generally `$_SERVER`).
16 * @return array Header/value pairs
18 function marshalHeadersFromSapi(array $server): array
20 $contentHeaderLookup = isset($server['LAMINAS_DIACTOROS_STRICT_CONTENT_HEADER_LOOKUP'])
21 ? static function (string $key): bool {
22 static $contentHeaders = [
23 'CONTENT_TYPE' => true,
24 'CONTENT_LENGTH' => true,
25 'CONTENT_MD5' => true,
27 return isset($contentHeaders[$key]);
29 : static fn(string $key): bool => str_starts_with($key, 'CONTENT_');
32 foreach ($server as $key => $value) {
33 if (! is_string($key)) {
41 // Apache prefixes environment variables with REDIRECT_
42 // if they are added by rewrite rules
43 if (str_starts_with($key, 'REDIRECT_')) {
44 $key = substr($key, 9);
46 // We will not overwrite existing variables with the
47 // prefixed versions, though
48 if (array_key_exists($key, $server)) {
53 if (str_starts_with($key, 'HTTP_')) {
54 $name = strtr(strtolower(substr($key, 5)), '_', '-');
55 $headers[$name] = $value;
59 if ($contentHeaderLookup($key)) {
60 $name = strtr(strtolower($key), '_', '-');
61 $headers[$name] = $value;