HTTP Request
Nette encapsulates the HTTP request into objects with a clear API while providing a sanitization filter.
The HTTP request is represented by the Nette\Http\Request object. If you are working with Nette,
this object is automatically created by the framework, and you can have it passed to you using dependency injection. In presenters, simply call the
$this->getHttpRequest()
method. If you are working outside the Nette Framework, you can create the object using RequestFactory.
A major advantage of Nette is that when creating the object, it automatically sanitizes all input parameters (GET, POST, COOKIE) as well as the URL, removing control characters and invalid UTF-8 sequences. You can then safely work with this data. The sanitized data is subsequently used in presenters and forms.
→ Installation and requirements
Nette\Http\Request
This object is immutable. It has no setters; it has only one so-called wither, withUrl()
, which does not change
the object but returns a new instance with the modified value.
withUrl (Nette\Http\UrlScript $url): Nette\Http\Request
Returns a clone with a different URL.
getUrl(): Nette\Http\UrlScript
Returns the URL of the request as a UrlScript object.
$url = $httpRequest->getUrl();
echo $url; // https://nette.org/en/documentation?action=edit
echo $url->getHost(); // nette.org
Warning: Browsers do not send the fragment to the server, so $url->getFragment()
will return an empty
string.
getQuery (?string $key=null): string|array|null
Returns GET request parameters.
$all = $httpRequest->getQuery(); // array of all URL parameters
$id = $httpRequest->getQuery('id'); // returns GET parameter 'id' (or null)
getPost (?string $key=null): string|array|null
Returns POST request parameters.
$all = $httpRequest->getPost(); // array of all POST parameters
$id = $httpRequest->getPost('id'); // returns POST parameter 'id' (or null)
getFile (string|string[] $key): Nette\Http\FileUpload|array|null
Returns an upload as a Nette\Http\FileUpload object:
$file = $httpRequest->getFile('avatar');
if ($file?->hasFile()) { // was any file uploaded?
$file->getUntrustedName(); // filename sent by the user
$file->getSanitizedName(); // name without dangerous characters
}
To access a nested structure, provide an array of keys.
//<input type="file" name="my-form[details][avatar]" multiple>
$file = $request->getFile(['my-form', 'details', 'avatar']);
Since you cannot trust external data and therefore rely on the structure of the files, this approach is safer than, for
example, $request->getFiles()['my-form']['details']['avatar']
, which might fail.
getFiles(): array
Returns a tree of all uploads in a normalized structure, where the leaves are Nette\Http\FileUpload objects:
$files = $httpRequest->getFiles();
getCookie (string $key): string|array|null
Returns a cookie or null
if it doesn't exist.
$sessId = $httpRequest->getCookie('sess_id');
getCookies(): array
Returns all cookies.
$cookies = $httpRequest->getCookies();
getMethod(): string
Returns the HTTP method used for the request.
$httpRequest->getMethod(); // GET, POST, HEAD, PUT
isMethod (string $method): bool
Tests the HTTP method used for the request. The parameter is case-insensitive.
if ($httpRequest->isMethod('GET')) // ...
getHeader (string $header): ?string
Returns an HTTP header or null
if it doesn't exist. The parameter is case-insensitive.
$userAgent = $httpRequest->getHeader('User-Agent');
getHeaders(): array
Returns all HTTP headers as an associative array.
$headers = $httpRequest->getHeaders();
echo $headers['Content-Type'];
isSecured(): bool
Is the connection encrypted (HTTPS)? Proper functionality might require setting up a proxy.
isSameSite(): bool
Is the request coming from the same (sub)domain and initiated by clicking a link? Nette uses the _nss
cookie
(formerly nette-samesite
) for detection.
isAjax(): bool
Is it an AJAX request?
getRemoteAddress(): ?string
Returns the user's IP address. Proper functionality might require setting up a proxy.
getRemoteHost(): ?string
Returns the DNS translation of the user's IP address. Proper functionality might require setting up a proxy.
getBasicCredentials(): ?array
Returns authentication credentials for Basic HTTP authentication.
[$user, $password] = $httpRequest->getBasicCredentials();
getRawBody(): ?string
Returns the body of the HTTP request.
$body = $httpRequest->getRawBody();
detectLanguage (array $langs): ?string
Detects the language. Pass an array of languages supported by the application as the $langs
parameter, and it will
return the one preferred by the visitor's browser. It's not magic; it just uses the Accept-Language
header. If no
match is found, it returns null
.
// Browser sends e.g., Accept-Language: cs,en-us;q=0.8,en;q=0.5,sl;q=0.3
$langs = ['hu', 'pl', 'en']; // languages supported by the application
echo $httpRequest->detectLanguage($langs); // en
RequestFactory
The Nette\Http\RequestFactory class is used to
create an instance of Nette\Http\Request
, which represents the current HTTP request. (If you are working with Nette,
the HTTP request object is automatically created by the framework.)
$factory = new Nette\Http\RequestFactory;
$httpRequest = $factory->fromGlobals();
The fromGlobals()
method creates the request object based on the current PHP global variables ($_GET
,
$_POST
, $_COOKIE
, $_FILES
, and $_SERVER
). When creating the object, it
automatically cleanses all input parameters (GET, POST, COOKIE) as well as the URL from control characters and invalid
UTF-8 sequences, ensuring security when working with this data later.
RequestFactory can be configured before calling fromGlobals()
:
- using the
$factory->setBinary()
method disables automatic cleansing of input parameters from control characters and invalid UTF-8 sequences. - using the
$factory->setProxy(...)
method specifies the IP address of the proxy server, which is necessary for correct detection of the user's IP address.
RequestFactory allows defining filters that automatically transform parts of the URL request. These filters remove unwanted characters from URLs that might have been inserted, for example, by incorrect implementations of comment systems on various websites:
// remove spaces from the path
$requestFactory->urlFilters['path']['%20'] = '';
// remove dot, comma, or right parenthesis from the end of the URI
$requestFactory->urlFilters['url']['[.,)]$'] = '';
// clean the path from double slashes (default filter)
$requestFactory->urlFilters['path']['/{2,}'] = '/';
The first key, 'path'
or 'url'
, determines which part of the URL the filter will be applied to. The
second key is the regular expression to search for, and the value is the replacement to be used instead of the found text.
Uploaded Files
The Nette\Http\Request::getFiles()
method returns an array of all uploads in a normalized structure, where the
leaves are Nette\Http\FileUpload objects. These
encapsulate the data submitted by the <input type=file>
form element.
The structure reflects the naming of elements in HTML. In the simplest case, it might be a single named form element submitted as:
<input type="file" name="avatar">
In this case, $request->getFiles()
returns an array:
[
'avatar' => /* FileUpload instance */
]
The FileUpload
object is created even if the user did not upload any file or the upload failed. The
hasFile()
method returns true if a file was sent:
$request->getFile('avatar')?->hasFile();
In the case of an element name using array notation:
<input type="file" name="my-form[details][avatar]">
the returned tree looks like this:
[
'my-form' => [
'details' => [
'avatar' => /* FileUpload instance */
],
],
]
You can also create arrays of files:
<input type="file" name="my-form[details][avatars][]" multiple>
In such a case, the structure looks like this:
[
'my-form' => [
'details' => [
'avatars' => [
0 => /* FileUpload instance */,
1 => /* FileUpload instance */,
2 => /* FileUpload instance */,
],
],
],
]
The best way to access index 1 of the nested array is as follows:
$file = $request->getFile(['my-form', 'details', 'avatars', 1]);
if ($file instanceof Nette\Http\FileUpload) {
// ...
}
Since you cannot trust external data and therefore rely on the structure of the files, this approach is safer than, for
example, $request->getFiles()['my-form']['details']['avatars'][1]
, which might fail.
Overview of FileUpload
Methods
hasFile(): bool
Returns true
if the user uploaded a file.
isOk(): bool
Returns true
if the file was uploaded successfully.
getError(): int
Returns the error code associated with the uploaded file. It is one of the UPLOAD_ERR_XXX constants. If the file was uploaded
successfully, it returns UPLOAD_ERR_OK
.
move (string $dest)
Moves an uploaded file to a new location. If the destination file already exists, it will be overwritten.
$file->move('/path/to/files/name.ext');
getContents(): ?string
Returns the contents of the uploaded file. If the upload was not successful, it returns null
.
getContentType(): ?string
Detects the MIME content type of the uploaded file based on its signature. If the upload was not successful or the detection
failed, it returns null
.
Requires the PHP extension fileinfo
.
getUntrustedName(): string
Returns the original file name as submitted by the browser.
Do not trust the value returned by this method. A client could send a malicious filename with the intention to corrupt or hack your application.
getSanitizedName(): string
Returns the sanitized file name. It contains only ASCII characters [a-zA-Z0-9.-]
. If the name does not contain
such characters, it returns 'unknown'
. If the file is a JPEG, PNG, GIF, WebP, or AVIF image, it also returns the
correct file extension.
Requires the PHP extension fileinfo
.
getSuggestedExtension(): ?string
Returns the appropriate file extension (without the dot) corresponding to the detected MIME type.
Requires the PHP extension fileinfo
.
getUntrustedFullPath(): string
Returns the original file path as submitted by the browser during directory upload. The full path is only available in PHP 8.1 and later. In previous versions, this method returns the original file name.
Do not trust the value returned by this method. A client could send a malicious filename with the intention to corrupt or hack your application.
getSize(): int
Returns the size of the uploaded file. If the upload was not successful, it returns 0
.
getTemporaryFile(): string
Returns the path to the temporary location of the uploaded file. If the upload was not successful, it returns
''
.
isImage(): bool
Returns true
if the uploaded file is a JPEG, PNG, GIF, WebP, or AVIF image. Detection is based on its signature
and does not verify the integrity of the entire file. Whether an image is corrupted can be determined, for example, by trying to
load it.
Requires the PHP extension fileinfo
.
getImageSize(): ?array
Returns a pair [width, height]
with the dimensions of the uploaded image. If the upload was not successful or it
is not a valid image, it returns null
.
toImage(): Nette\Utils\Image
Loads the image as an Image object. If the upload was not successful or it
is not a valid image, it throws an Nette\Utils\ImageException
.