Search by

nabeghe / headers-reader

nabeghe

A lightweight, robust PHP library to read, inspect, and parse HTTP headers with getallheaders and $_SERVER fallback.

Package info

github.com/nabeghe/headers-reader-php

pkg:composer/nabeghe/headers-reader

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

Stars: 3

Open Issues: 0

v2.0.0 2025-07-03 12:21 UTC

This package is auto-updated.

Last update: 2026-09-27 22:12:38 UTC


README

A lightweight, robust PHP library to read, inspect, and parse HTTP headers with getallheaders() and automatic $_SERVER fallback.

Supports PHP 7.4 through PHP 8.5+.

๐Ÿš€ Features

  • Reliable header extraction: Uses getallheaders() when available, with automatic fallback to $_SERVER (works seamlessly in CLI, testing, Nginx FastCGI, and Apache environments).
  • Apache Authorization support: Automatically captures Authorization headers even when stripped by Apache/FastCGI (HTTP_AUTHORIZATION / REDIRECT_HTTP_AUTHORIZATION).
  • Case-insensitive & flexible: Headers can be retrieved using any case or hyphen/underscore style (x-api-key, X-Api-Key, or x_api_key).
  • Bearer Token helper: Direct extraction of Bearer tokens via Headers::bearerToken().
  • Type casting: Built-in helpers for int and bool values.
  • Header filtering: Fetch subsets using only() or except().
  • Test-friendly: Easily mock or override headers with set(), remove(), setHeaders(), and flush().
  • Zero dependencies & fully backward-compatible.

๐Ÿ“ฆ Installation

Install the package via Composer:

composer require nabeghe/headers-reader

๐Ÿซก Usage

Example 1 - Basic Usage

use Nabeghe\HeadersReader\Headers;

// Get a header (case-insensitive) with an optional default value
echo Headers::get('Content-Type');
echo Headers::get('X-Custom-1', 'Default value');

// Check if a header exists
if (Headers::has('Authorization')) {
    // Extract Bearer token directly
    $token = Headers::bearerToken();
}

// Retrieve all headers as an associative array with lowercase keys
$allHeaders = Headers::all();

// Clear the cached headers
Headers::flush();

Example 2 - Custom Class with Default Values

You can extend Headers to configure default values per header or a general fallback default. Key matching for DEFAULTS is fully case-insensitive.

use Nabeghe\HeadersReader\Headers;

class MyHeaders extends Headers
{
    public const DEFAULT = 'The general default value';

    public const DEFAULTS = [
        'X-Custom-1' => 'The default value for X-Custom-1',
        'X-Custom-2' => 'The default value for X-Custom-2',
        'X-Custom-3' => 'The default value for X-Custom-3',
        'X-Custom-4' => 'The default value for X-Custom-4',
    ];
}

echo 'X-Custom-1: ' . MyHeaders::get('X-Custom-1') . "\n<br>";
echo 'X-Custom-2: ' . MyHeaders::get('x-custom-2') . "\n<br>"; // Case-insensitive matching
echo 'X-Custom-5: ' . MyHeaders::get('X-Custom-5') . "\n<br>"; // Falls back to DEFAULT

Example 3 - Typed Retrieval & Filtering

use Nabeghe\HeadersReader\Headers;

// Get integer values (useful for Content-Length, RateLimit headers, etc.)
$length = Headers::int('Content-Length', 0);

// Get boolean values ('1', 'true', 'yes', 'on' -> true)
$isDebug = Headers::bool('X-Debug-Mode', false);

// Retrieve only specific headers
$filtered = Headers::only(['content-type', 'authorization']);

// Retrieve all headers except sensitive ones
$safeHeaders = Headers::except(['authorization', 'cookie']);

Example 4 - Testing & Mocking

Ideal for unit tests, CLI scripts, or middleware:

use Nabeghe\HeadersReader\Headers;

// Mock all headers
Headers::setHeaders([
    'Host' => 'example.com',
    'Authorization' => 'Bearer secret-jwt-token',
]);

// Set or overwrite a specific header
Headers::set('X-Test', '123');

// Remove a header
Headers::remove('X-Test');

// Reset cache after tests
Headers::flush();

๐Ÿงช Testing

Run PHPUnit tests:

composer test
# or
vendor/bin/phpunit

๐Ÿ“– License

Licensed under the MIT license, see LICENSE.md for details.