Luminova Framework

PHP Luminova: Incoming HTTP Request Management Class

Last updated: 2024-10-03 20:24:07

The Request class plays a crucial role in web applications by providing a structured and simple way to handle incoming HTTP requests and responses, providing methods for safe access and manipulation.

The Request class represents an incoming HTTP request to a server, encapsulating various components such as headers, query parameters, form data, and uploaded files. This class offers a structured approach to access and manipulate incoming HTTP requests, including built-in authentication mechanisms to validate requests based on origin, proxies, or allowed domains.

Accessing the Request Object

The request object can be accessed in multiple ways, depending on the context. You can use the global helper function, the Factory class, or the Controller class.

Access Methods

1. Using Global Helper Function

$request = request();

2. Accessing Through the Factory Class

use Luminova\Application\Factory;

$request = Factory::request();

3. Initializing the Request Instance Directly

use Luminova\Http\Request;

$request = new Request();

4. Accessing in Controller Classes

If your controller extends BaseController:

$this->request->foo();

If your controller extends BaseViewController, you can access it in two ways:

Direct Access:

$this->request()->foo();

Initializing in the onCreate Method:

You can initialize the request instance once, then access it later:

$this->request(); // Initialize

// Then access it.
$this->request->foo();

Properties

server

Http server instance.

public ?\Luminova\Http\Server $server = null;

header

Http request header instance.

public ?\Luminova\Http\Header $header = null;

agent

Browser request user-agent information.

public ?\Luminova\Http\UserAgent $agent = null;

Methods

constructor

Initializes a new Request object, representing an HTTP request.

This constructor optionally accept request properties like method, URI, body, files, raw body, server variables, and headers. allowing you to create a custom HTTP request.

public function __construct(
        private ?string $method = null,
        private ?string $uri = null,
        private array $body = [],
        private array $files = [],
        private ?string $raw = null,
        ?array $server = null,
        ?array $headers = null
)

Parameters:

ParameterTypeDescription
$methodstring|nullOptional HTTP method used for the request (e.g., 'GET', 'POST')..
$uristring|nullOptional request URI, typically the path and query string.
$bodyarray<string,mixed>Optional request body, provided as an associative array (e.g., ['field' => 'value']).
This may include form data, JSON, etc..
$filesarray<string,mixed>Optional request files, provided as an associative array (e.g., ['field' => array|string]).
$rawstring|nullOptional request raw-body string.
$serverarray<string,mixed>|nullOptional server variables (e.g., $_SERVER).
If not provided, defaults to global $_SERVER..
$headersarray<string,mixed>|nullOptional associative array of HTTP headers.
If not provided, headers request headers will be extracted from apache_request_headers or $_SERVER.

Example

Create a new request-response object by passing appropriate values.

$request = new Luminova\Http\Request(
    method: 'POST',
    uri: '/api/v1/users',
    body: ['name' => 'John Doe', 'email' => '[email protected]'], 
    files: [
        'image' => [
            'name' => 'profile.jpg',
            'type' => 'image/jpeg',
            'tmp_name' => '/tmp/phpYzdqkD',
            'error' => 0,
            'size' => 123456
        ]
    ],
    raw: null,
    server: [
        'REQUEST_METHOD' => 'POST',
        'REMOTE_ADDR' => '192.168.1.10',
        'HTTP_USER_AGENT' => 'Mozilla/5.0',
        'SERVER_PROTOCOL' => 'HTTP/1.1',
        'SERVER_NAME' => 'example.com',
        'REQUEST_URI' => '/api/v1/users',
    ],
    headers: [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer some-token',
        'Accept' => 'application/json',
        'X-Custom-Header' => 'CustomValue'
    ] 
);

toString

Converts the request body to a raw string format based on the content type.

public toString(): string

Return Value:

string - Return the raw string representation of the request body.

Supported Content Types:

  • application/x-www-form-urlencoded: Converts the body to a URL-encoded query string.
  • application/json: Converts the body to a JSON string.
  • multipart/form-data: Converts the body to a multipart/form-data format.

toMultipart

Converts the request body to a multipart/form-data string format.

public toMultipart(): string

Return Value:

string - Return the multipart form-data representation of the request body.


getGet

Get a field value from HTTP GET request method or entire fields if $field parameter is null.

public getGet(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getPost

Get a field value from HTTP POST request method or entire fields if $field parameter is null.

public getPost(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getPut

Get a value from the PUT request or entire fields if $field parameter is null.

public getPut(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getOptions

Get a value from the OPTIONS request or entire fields if $field parameter is null.

public getOptions(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getPatch

Get a value from the PATCH request method or entire fields if $field parameter is null.

public getPatch(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getHead

Get a value from the HEAD request method or entire fields if $field parameter is null.

public getHead(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getConnect

Get a value from the CONNECT request method or entire fields if $field parameter is null.

public getConnect(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getTrace

Get a value from the TRACE request method or entire fields if $field parameter is null.

public getTrace(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getPropfind

Get a value from the PROPFIND request method or entire fields if $field parameter is null.

public getPropfind(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getMkcol

Get a value from the MKCOL request method or entire fields if $field parameter is null.

public getMkcol(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getCopy

Get a value from the COPY request method or entire fields if $field parameter is null.

public getCopy(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getMove

Get a value from the MOVE request method or entire fields if $field parameter is null.

public getMove(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getLock

Get a value from the LOCK request method or entire fields if $field parameter is null.

public getLock(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getUnlock

Get a value from the UNLOCK request method or entire fields if $field parameter is null.

public getUnlock(string|null $field, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$fieldstring|nullThe field key to retrieve the value value from.
$defaultmixedAn optional default value to return if the field is not found (default: null).

Return Value:

mixed - Return the value from HTTP request method body based on field name.


getArray

Get a value from the request body as an array.

public getArray(string $method, string $field, array $default = []): array

Parameters:

ParameterTypeDescription
$methodstringThe HTTP request method (e.g, GET, POST, etc..).
$fieldstringThe request body field name to return.
$defaultarrayOptional default value to return (default: []).

Return Value:

array - Return array of HTTP request method key values.

Throws:


getBody

Get the entire request body as an Array or JSON object.

public getBody(bool $object = false): array|object

Parameters:

ParameterTypeDescription
$objectboolWhether to return an array or a json object (default: false).

Return Value:

array|object - Return the request body as an array or json object.


getFile

Get an uploaded file object by its input name.

public getFile(string $name, ?int $index = null): File[]|File|null

Parameters:

ParameterTypeDescription
$namestringThe file input field name.
$indexint|nullOptional file index for multiple files (default: null).

Return Value:

array<int, \Luminova\Http\File>|\Luminova\Http\File|null - Return uploaded file instance or null if file input name not found.

See Also:

To learn more about File Upload Object, refer to the documentation.


getFiles

Get irritable array of uploaded files information.

public getFiles(): array

Return Value:

array<string,array> - Return an array containing uploaded files information.

Array Structure for Multiple File Uploads

[
    'images' => [
        'name' => ['file1.jpg', 'file2.png', 'file3.gif'],
        'type' => ['image/jpeg', 'image/png', 'image/gif'],
        'tmp_name' => ['/tmp/phpYzdqkD', '/tmp/phpeEwEWq', '/tmp/php7sdfXy'],
        'error' => [0, 0, 0],
        'size' => [123456, 234567, 345678]
    ]
];

Using the generator to process files

Generator function to yield File objects one by one.

// /app/Utils/Global.php
<?php
use Luminova\Http\File;

function getFilesGenerator(array $files): \Generator 
{
    foreach ($files['images']['name'] as $index => $name) {
        $extension = pathinfo($name, PATHINFO_EXTENSION);

        // Get the actual MIME type from the temp file
        $mime = get_mime($temp);

        // Yield a new File object
        yield new File(
            $index,
            $name,
            $files['images']['type'][$index],
            (int) $files['images']['size'][$index],
            $mime ?: null,
            $extension ?: '',
            $files['images']['tmp_name'][$index],
            $files['images']['error'][$index]
        );
    }
}

Process each File object as it is yielded

<?php
use Luminova\Storages\Uploader;

foreach (getFilesGenerator($request->getFiles()) as $file) {
    if($file->valid()){
        $file->setConfig([
            'upload_path' => root('writeable/storages/foo/'),
            'if_existed' => $file::IF_EXIST_OVERWRITE
        ]);

        $status = Uploader::upload($file);
    }
}

Benefits of yield:

  • Memory Efficiency: Especially useful when dealing with large file uploads, as it avoids storing all the File objects in memory at once.
  • On-demand Processing: Only the file currently being processed needs to be in memory, which is more efficient than loading all files at once.

When to Use yield:

  • If you're dealing with a large number of files or large file sizes, and you want to avoid memory overhead.
  • When you don't need to access all File objects simultaneously, but rather process them one-by-one (e.g., uploading, saving, or validating them).

getMethod

Get the current request method.

public getMethod(): string

Return Value:

string - Return the HTTP request method.


isGet

Check if the request method is GET.

public isGet(): bool

Return Value:

bool - Returns true if the request method is GET, false otherwise.


isPost

Check if the request method is POST.

public isPost(): bool

Return Value:

bool - Returns true if the request method is POST, false otherwise.


isMethod

Check if the request method is the provided method.

public isMethod(string $method): bool

Parameters:

ParameterTypeDescription
$methodstringThe method to check against (e.g, POST, GET).

Return Value:

bool - Returns true if the request method matches the provided method, false otherwise.


getContentType

Get the request content type.

public getContentType(): string

Return Value:

string - Return the request content type or blank string if not available.


getAuth

Get HTTP request header authorization from (e.g, HTTP_AUTHORIZATION, Authorization or REDIRECT_HTTP_AUTHORIZATION).

public getAuth(): ?string

Return Value:

string|null - Return the authorization header value or null if no authorization header was sent.


Return Value:

bool - Return true if the request was made from the command line.


isSecure

Check if the current request connection is secure.

public isSecure(): bool

Return Value:

bool - Return true if the connection is secure false otherwise.


isAJAX

Check if request is ajax request, see if a request contains the HTTP_X_REQUESTED_WITH header.

public isAJAX(): bool

Return Value:

bool - Return true if request is ajax request, false otherwise


isApi

Check if the request URL indicates an API request endpoint.This method checks if the URL path prefix matched any of /api or public/api or your custom defined API URL prefix.

public isApi(): bool

Return Value:

bool - Returns true if the URL indicates an API endpoint, false otherwise.


getQuery

Get the request URL query string.

public getQuery(): string

Return Value:

string - Return the request URL query parameters as string.


getQueries

Get current URL query parameters as an associative array using the parameter name as key.

public getQueries(): array&lt;string,mixed&gt;

Return Value:

array<string,mixed> - Return the request URL query parameters as an array.


getUrl

Get the full URL of the current request, including the scheme, host and query parameters. (e.g, https://example.com/foo/bar?query=123)

public getUrl(): string

Return Value:

string - Return the full URL of the request.


getUri

Get the URI (path and query string) of the current request (e.g, /foo/bar?query=123).

public getUri(): string

Return Value:

string - Return the URI of the request (path and query string).


getPaths

Get current request URL path information.

public getPaths(): string

Return Value:

string - Return the request URL paths.


getRequestUri

Returns un-decoded request URI, path and query string.

public getRequestUri(): string

Return Value:

string - Return the raw request URI (i.e. URI not decoded).


getHost

Get current request hostname without port, if allowed host is set it will check if host is in allowed list or patterns.

public getHost(bool $extension = false): string

Parameters:

ParameterTypeDescription
$extensionboolWeather to throw an exception if invalid host or not allowed host (default: false).

Return Value:

string - Throw if host is invalid or not allowed.

Throws:


getHostname

Get current request hostname with port if port is available.If allowed host is set it will check if host is in allowed list or patterns.

public getHostname(bool $extension = false, bool $port = true): string

Parameters:

ParameterTypeDescription
$extensionboolWeather to throw an exception if invalid host or not allowed host (default: false).
$portboolWeather to return hostname with port (default: true).

Return Value:

string - Return request hostname and port.

Throws:


getOrigin

Get the request origin domain, if the list of trusted origin domains are specified, it will check if the origin is a trusted origin domain.

public getOrigin(): ?string

Return Value:

string|null - Return the request origin domain if found and trusted, otherwise null.


getPort

Get the request origin port from X_FORWARDED_PORT or SERVER_PORT if available.

public getPort(): int|string|null

Return Value:

int|string|null - Return either a string if fetched from the server available, or integer, otherwise null.

Check if X-Forwarded-Port header exists and use if available.If not available check for server-port header if also not available return NULL as default.


getScheme

Gets the request scheme name.

public getScheme(): string

Return Value:

string - Return request scheme, if secured return https otherwise http.


getProtocol

Gets the request server protocol name and version (e.g: HTTP/1.1).

public getProtocol(string $default = 'HTTP/1.1'): string

Parameters:

ParameterTypeDescription
$defaultstringThe default server protocol to return if no available (default: HTTP/1.1).

Return Value:

string - Return Request protocol name and version, if available, otherwise default is return HTTP/1.1.


getBrowser

Get the request browser name and platform from user-agent information.

public getBrowser(): string

Return Value:

string - Return browser name and platform.


getUserAgent

Get request browser user-agent information.

public getUserAgent(?string $useragent = null): UserAgent

Parameters:

ParameterTypeDescription
$useragentstring|nullThe User Agent string, if not provided, it defaults to (HTTP_USER_AGENT).

Return Value:

UserAgent - Return instance user-agent class containing browser information.


isSameOrigin

Check if the request origin matches the current application host.

public isSameOrigin(bool $subdomains = false): bool

Parameters:

ParameterTypeDescription
$subdomainsboolWhether to consider sub-domains or not (default: false).

Return Value:

bool - Returns true if the request origin matches the current host, false otherwise.


isTrusted

Validates if the given (hostname, origin, proxy ip or subnet) matches any of the trusted patterns.

public static isTrusted(string $input, string $context = 'hostname'): bool

Parameters:

ParameterTypeDescription
$inputstringThe domain, origin or IP address to check.
$contextstringThe context to check input for (e.g, hostname).

Return Value:

bool - Return true if the input is trusted, false otherwise.

Throws:

Supported Context:

  • hostname - Validates a host name.
  • origin - Validates an origin hostname.
  • proxy Validates an IP address or proxy.

Note: This will consider the defined configuration in App\Config\Security during validation.


isTrustedProxy

Check whether this request origin IP address is from a trusted proxy.

public isTrustedProxy(): bool

Return Value:

bool - Return true if the request origin IP address is trusted false otherwise.


isTrustedOrigin

Check whether this request origin is from a trusted origins.

public isTrustedOrigin(): bool

Return Value:

bool - Return true if the request origin is trusted false otherwise.