PHP Luminova: Managing Incoming HTTP Request Headers
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
- Class namespace:
Luminova\Http\Header - This class implements: Luminova\Interface\LazyObjectInterface, \Countable
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');Check if a key exists:
if ($header->has('Accept-Encoding')) {
// Key exists
}Count the number of elements:
$count = $header->count();Methods
PHP output buffering is managed by Runtime.
constructor
Initializes the header constructor.
Pass server-style keys such as HTTP_USER_AGENT or CONTENT_TYPE. Null or an empty array reads the current request headers.
public function __construct(?array $headers = null)Parameters:
| Parameter | Type | Description |
|---|---|---|
$headers | array<string, mixed>|null | Optional server variables to extract headers from. |
get
Retrieves the value of a specific header or all headers if no name is provided.
/**
* @return mixed|array<array-key, mixed>|string|null
*/
public function get(?string $name = null, mixed $default = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string|null | Stored header name, using its exact case. |
$default | mixed | Fallback value when the named header is absent. |
Return:
mixed - Return the value of the specified header, or all headers if $name is null.
all
Retrieve all stored headers.
public function all(): arrayReturn:
array<string,mixed> - Returns the stored headers keyed by name, or an empty array if none are stored.
many
Retrieve several stored headers by their exact names. Missing headers are skipped by default. Pass false as $skipMissing to include missing names with a null value.
public function many(array $names, bool $skipMissing = true): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$names | string[] | Header names to retrieve. |
$skipMissing | bool | Whether to omit missing headers. Defaults to true. |
Return:
array<string,mixed> - Returns header values keyed by the requested names. An empty list of names returns an empty array.
set
Sets the value for a specific header.
public function set(string $key, mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The header key to set. |
$value | mixed | The value to set for the header key. |
Return:
self - Returns the current instance.
remove
Removes a specific header by its key.
public function remove(string $key): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The key of the header to remove. |
has
Checks if a specific header key exists.
public function has(string $key): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The header key to check. |
Return:
bool - Return true if the key exists, false otherwise.
count
Gets the total number of header variables.
public function count(): intReturn:
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 function send(
array $headers,
bool $ifNotSent = true,
bool $charset = false,
?int $status = null,
?bool $enforceCors = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$headers | array<string, string|int|float> | Headers to send. |
$ifNotSent | bool | Skip sending if headers are already sent (default: true). |
$charset | bool | Append charset to Content-Type if missing (default: false). |
$status | int|null | HTTP status code to send (default: null). |
$enforceCors | bool|null | Enforce the configured CORS policy, or let the framework decide when null. |
Throws:
RuntimeException- When headers are already sent and debugging is enabled.
parse
Normalize headers without sending them.
Behavior:
- Applies system default headers when
X-System-Default-Headersis 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 function parse(array $headers, bool $applyCors = false): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$headers | array<string, mixed> | Headers to normalize. |
$applyCors | bool | Apply the configured CORS policy (default: false). |
Return:
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 function sendNoCacheHeaders(
int $status = 200,
string|bool|null $contentType = null,
string|int|null $retry = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$status | int | HTTP status code to send (default: 200). |
$contentType | string|bool|null | Optional content type (default: 'text/html'). |
$retry | string|int|null | Optional value for Retry-After header. |
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 range before sending it using the http_response_code function. It also sets the REDIRECT_STATUS superglobal.
public static function sendStatus(int $code): bool Parameters:
| Parameter | Type | Description |
|---|---|---|
$code | int | The HTTP response status code to send. |
Return:
bool - Return true if status code is valid and set, false otherwise.
getHeaders
Extracts all request headers using apache_request_headers or the $_SERVER variables.
public static function getHeaders(): arrayReturn:
array<string,string> - Return the request headers.
extractHeaders
Parse _SERVER variables and extract headers from it.
public static function extractHeaders(array $variables): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$variables | array<string,mixed> | Server variables to extract headers from. |
Return:
array<string,string> - Return the parsed headers.
findAllowedOriginDomain
Retrieve the allowed origin based on configuration.
- Returns
*if all origins are allowed. - Returns the matching origin if it is explicitly allowed.
- Returns
nullif the origin is forbidden or missing whenforbidEmptyOriginis enabled.
public static function findAllowedOriginDomain(?string $origin = null): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$origin | string|null | Optional origin to check. Defaults to $_SERVER['HTTP_ORIGIN']. |
Return:
string|null - Returns the allowed origin, * for all, or null if forbidden.
isOriginAllowed
Determine whether a given origin is allowed based on application API configuration.
public static function isOriginAllowed(?string $origin = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$origin | string|null | Optional origin to check. Defaults to $_SERVER['HTTP_ORIGIN']. |
Return:
bool - Returns true if the origin is allowed, false otherwise.
isHeadersAllowed
Validates request headers against allowed headers, based on application API configuration.
public static function isHeadersAllowed(?array $headers = null, ?string &$match = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$headers | array<string, string|int|float>|null | The request headers to validate. |
$match | string|null | The matched header that is not allowed. |
Return:
bool - Return true if all headers are valid, false otherwise.
toHeaderName
Convert an uppercase server key such as HTTP_X_REQUEST_ID to X-Request-Id. The method also handles CONTENT_TYPE and CONTENT_LENGTH.
public static function toHeaderName(string $name): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | Server variable name. |
Return:
string - Returns the converted header name.
isHeaderName
Check whether a server variable name denotes an HTTP header. The check is case-insensitive.
public static function isHeaderName(string $name): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | Server variable name. |
Return:
bool - Returns true for an HTTP-prefixed variable, either content variable, or REDIRECT_HTTP_AUTHORIZATION.
getDefault
Build the framework’s default response headers. A secure request also gets a Strict-Transport-Security header.
public static function getDefault(?string $contentType = 'text/html'): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$contentType | string\|null | Response media type. Use null to omit the Content-Type header. |
Return:
array<string,string> - Returns the default headers keyed by name.
getNoCacheHeaders
Build response headers that prevent caches from storing or reusing the response.
public static function getNoCacheHeaders(
?string $contentType = null,
?int $retry = null
): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$contentType | string\|null | Response media type. Use null to omit the Content-Type header. |
$retry | int\|null | Optional Retry-After delay in seconds. |
Return:
array<string,string|int> - Returns the no-cache headers, including Retry-After when a delay is supplied.
sendNoContentHeaders
Send status 204 with no-cache headers. The helper skips sending when headers have already been sent.
public static function sendNoContentHeaders(string|int|null $retry = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$retry | int\|null | Optional Retry-After delay in seconds. Pass an integer or null. |
normalize
Convert scalar or null header values to strings, trim spaces and tabs, and validate the results. Null becomes an empty string.
public static function normalize(mixed $values, bool $withName = false): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$values | scalar\|null\|array<array-key,scalar\|null> | One value or a non-empty collection of values. |
$withName | bool | Validate and preserve header names when true. |
Return:
array<string,string>|string[] - Returns the normalized values, keyed by header name when requested.
Throws:
Luminova\Exceptions\InvalidArgumentException- If the array is empty or a header name or value is invalid.
assert
Validate a single HTTP header name or value.
public static function assert(mixed $value, bool $isValue = true): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$value | mixed | Header name or value to validate. |
$isValue | bool | Validate a value when true or a name when false. |
Throws:
Luminova\Exceptions\InvalidArgumentException- If the value violates the header syntax.