Luminova Framework

PHP Luminova: Managing Incoming HTTP Request Headers

Last updated: 2025-12-28 09:51:37

The header class specifically focuses on managing request headers. It provides methods to interact with and manage request headers easily.

The HTTP Header class allows you to manage request headers, similar to the way the Luminova\Http\Server class that handles server-parameters. It provides methods to interact with, retrieve, and manipulate request headers, simplifying the process of managing HTTP requests.


Class Definition


Examples:

The Header object is available in the Request class object as a public property $request->header.

Get the value for a specific key:

$value = $header->get('User-Agent');

Set a new value for a key:

$header->set('User-Agent', 'New User Agent');

Remove a key:

$header->remove('Accept');

Search for a value:

$key = $header->search('Host');

Check if a key exists:

if ($header->has('Accept-Encoding')) {
    // Key exists
}

Count the number of elements:

$count = $header->count();

Methods

constructor

Initializes the header constructor.

The constructor accepts an optional headers. If no headers are passed, it will use the request headers.

public __construct(?array $variables = null): mixed

Parameters:

ParameterTypeDescription
$variablesarray<string,mixed>|nullOptional key-value pairs of header variables.

get

Retrieves the value of a specific header or all headers if no name is provided.

public get(?string $name = null, mixed $default = null): mixed|array|string|null

Parameters:

ParameterTypeDescription
$namestring|nullOptional name of the server variable.
$defaultmixedDefault value for the server key.

Return Value:

mixed|array|string|null - Return the value of the specified header, or all headers if $name is null.


set

Sets the value for a specific header.

public set(string $key, mixed $value): void

Parameters:

ParameterTypeDescription
$keystringThe header key to set.
$valuestringThe value to set for the header key.

remove

Removes a specific header by its key.

public remove(string $key): void

Parameters:

ParameterTypeDescription
$keystringThe key of the header to remove.

has

Checks if a specific header key exists.

public has(string $key): bool

Parameters:

ParameterTypeDescription
$keystringThe header key to check.

Return Value:

bool - Return true if the key exists, false otherwise.


count

Gets the total number of header variables.

public count(): int

Return Value:

int - Return the number of header variables.


send

Send HTTP headers to the client.

Handles safe header dispatch with optional REST validation and CORS checks.Prevents duplicate header output and provides clear diagnostics when headerswere already sent.

Behavior:

  • Optionally aborts if headers were already sent.
  • Sends HTTP status code when provided.
  • Removes entity headers for 204 / 304 responses.
  • Appends charset to Content-Type when missing (optional).
  • Optionally validates headers for API / REST requests.
public static send(
    array<string,string|int|float> $headers,
    bool $ifNotSent = true,
    bool $charset = false,
    ?int $status = null,
    ?bool $validateRequestHeaders = null
): void

Parameters:

ParameterTypeDescription
$headersarray<string,string|int|float>Headers to send.
$ifNotSentboolSkip sending if headers are already sent (default: true).
$charsetboolAppend charset to Content-Type if missing (default: false).
$statusint|nullHTTP status code to send (default: null).
$validateRequestHeadersbool|nullEnable REST header validation (auto-detect if null).

Throws:


parse

Normalize headers without sending them.

Behavior:

  • Applies system default headers when X-System-Default-Headers is present.
  • Optionally validates REST / API headers.
  • Appends charset to Content-Type when missing.
  • Returns an empty array when headers are already valid or unchanged.
public static parse(array<string,mixed> $headers, bool $validateRequestHeaders = false): array<string,mixed>

Parameters:

ParameterTypeDescription
$headersarray<string,mixed>Headers to normalize.
$validateRequestHeadersboolEnable REST request header validation (default: false).

Return Value:

array<string,mixed> - Returns the normalized headers, or empty array if no changes are required.


sendNoCacheHeaders

Send no-cache HTTP headers.

This method sends HTTP headers to disable caching and optionally set content type and retry behavior.

public static sendNoCacheHeaders(
    int $status = 200, 
    string|bool|null $contentType = null, 
    string|int|null $retry = null
): void

Parameters:

ParameterTypeDescription
$statusintHTTP status code to send (default: 200).
$contentTypestring|bool|nullOptional content type (default: 'text/html').
$retrystring|int|nullOptional value for Retry-After header.

Return Value:

void - > Used by router and template rendering to prevent caching.


sendStatus

Sends HTTP response status code if it is valid.

This method checks if the provided status code is within the valid HTTP status code rangebefore sending it using the http_response_code function. It also sets the REDIRECT_STATUS superglobal.

static function sendStatus(int $code): bool 

Parameters:

ParameterTypeDescription
$codeintThe HTTP response status code to send.

Return Value:

bool - Return true if status code is valid and set, false otherwise.


terminate

Terminates the request by sending a status and formatted message.

Responds according to the Accept header:

  • application/json → JSON response
  • application/xml / text/xml → XML response
  • text/html → HTML page
  • fallback → plain text
public static terminate(
    int $status,
    string $message,
    ?string $title = null,
    int $retry = 3600
): void

Parameters:

ParameterTypeDescription
$statusintHTTP status code.
$messagestringTermination message.
$titlestring|nullOptional error title.
$retryintOptional cache retry duration in seconds (default: 3600).

getHeaders

Extracts all request headers using apache_request_headers or the $_SERVER variables.

public static getHeaders(): array<string,string>

Return Value:

array<string,string> - Return the request headers.


getFromGlobal

Parse _SERVER variables and extract headers from it.

public static getFromGlobal(?array $server = null): array<string,string>

Parameters:

ParameterTypeDescription
$serverarray<string,mixed>An optional custom server variable.

Return Value:

array<string,string> - Return the parsed headers.


getAllowedOrigin

Retrieve the allowed origin based on configuration.

  • Returns * if all origins are allowed.
  • Returns the matching origin if it is explicitly allowed.
  • Returns null if the origin is forbidden or missing when forbidEmptyOrigin is enabled.
public static getAllowedOrigin(?string $origin = null): ?string

Parameters:

ParameterTypeDescription
$originstring|nullOptional origin to check. Defaults to $_SERVER['HTTP_ORIGIN'].

Return Value:

string|null - Returns the allowed origin, * for all, or null if forbidden.


clearOutputBuffers

Clear or flush PHP output buffers with flexible modes.

Modes:

  • auto (default): Clears all but the base buffer if multiple exist; otherwise clears the top buffer.
  • all: Clears every active buffer down to the specified limit (default 0 for all).
  • top: Clears only the top-most buffer.
  • flush: Flushes the top-most buffer without clearing it.
public static clearOutputBuffers(string $mode = 'auto', int $limit = 0): bool

Parameters:

ParameterTypeDescription
$modestringHow to clear buffers: 'auto', 'all', 'top', or 'flush'.
$limitintMinimum buffer level to preserve (0 clears everything).

Return Value:

bool - Returns true if any buffer was cleared or flushed; false if no buffers existed.


isAllowedOrigin

Determine whether a given origin is allowed based on application API configuration.

public static isAllowedOrigin(?string $origin = null): bool

Parameters:

ParameterTypeDescription
$originstring|nullOptional origin to check. Defaults to $_SERVER['HTTP_ORIGIN'].

Return Value:

bool - Returns true if the origin is allowed, false otherwise.


isAllowedHeaders

Validates request headers against allowed headers, based on application API configuration.

public static isAllowedHeaders(array<string,string|int|float>|null $headers = null, ?string &$match = null): bool

Parameters:

ParameterTypeDescription
$headersarray<string,string|int|float>|nullThe request headers to validate.
$matchstring|nullThe matched header that is not allowed.

Return Value:

bool - Return true if all headers are valid, false otherwise.


setOutputHandler

Initializes the output buffer with the appropriate content-encoding handler.

This method is a wrapper around ob_start(). It detects supported encodings(such as gzip or deflate) from the client’s request headers and appliesthe proper output handler when compression is enabled and supported. If nomatching encoding is found, it falls back to a custom or default handler.

If output buffering is already active, it will not be restarted.

public static setOutputHandler(bool $clearIfSet = false, bool $withHandler = true): bool

Parameters:

ParameterTypeDescription
$clearIfSetboolWhether to clear existing output buffers when one is already active (default: false).
$withHandlerboolWhether to apply an output handler (default: true).

Return Value:

bool - Returns true if a new output buffer is started, false otherwise.