Nette Documentation Preview

syntax
HTTP Request
************

.[perex]
Nette encapsulates the HTTP request into objects with an understandable API while providing a sanitization filter.

Installation:

```shell
composer require nette/http
```

An HTTP request is an [api:Nette\Http\Request] object, which you get by passing it using [dependency injection |dependency-injection:passing-dependencies]. In presenters simply call `$httpRequest = $this->getHttpRequest()`.

What is important is that Nette when [creating|#RequestFactory] this object, it clears all GET, POST and COOKIE input parameters as well as URLs of control characters and invalid UTF-8 sequences. So you can safely continue working with the data. The cleaned data is then used in presenters and forms.


Nette\Http\Request
==================

This class is immutable, ie. it has no setters.


getUrl(): Nette\Http\UrlScript .[method]
----------------------------------------
Returns the URL of the request as object [UrlScript|urls#UrlScript].

```php
$url = $httpRequest->getUrl();
echo $url; // https://nette.org/en/documentation?action=edit
echo $url->getHost(); // nette.org
```

Browsers do not send a fragment to the server, so `$url->getFragment()` will return an empty string.


getQuery(string $key=null, $default=null): string|array|null .[method]
----------------------------------------------------------------------
Returns GET request parameters:

```php
$all = $httpRequest->getQuery();    // array of all URL parameters
$id = $httpRequest->getQuery('id'); // returns GET parameter 'id' (or null)
```


getPost(string $key=null, $default=null): string|array|null .[method]
---------------------------------------------------------------------
Returns POST request parameters:

```php
$all = $httpRequest->getPost();     // array of all POST parameters
$id = $httpRequest->getPost('id');  // returns POST parameter 'id' (or null)
```


getFile(string $key): Nette\Http\FileUpload|array|null .[method]
----------------------------------------------------------------
Returns [upload|#Uploaded Files] as object [api:Nette\Http\FileUpload]:

```php
$file = $httpRequest->getFile('avatar');
if ($file->hasFile()) { // was any file uploaded?
	$file->getName(); // name of the file sent by user
	$file->getSanitizedName(); // the name without dangerous characters
}
```


getFiles(): array .[method]
---------------------------
Returns tree of [upload files|#Uploaded Files] in a normalized structure, with each leaf an instance of [api:Nette\Http\FileUpload]:

```php
$files = $httpRequest->getFiles();
```


getCookie(string $key, $default=null): string|array|null .[method]
------------------------------------------------------------------
Returns a cookie or `null` if it does not exist.

```php
$sessId = $httpRequest->getCookie('sess_id');
```


getCookies(): array .[method]
-----------------------------
Returns all cookies:

```php
$cookies = $httpRequest->getCookies();
```


getMethod(): string .[method]
-----------------------------
Returns the HTTP method with which the request was made.

```php
echo $httpRequest->getMethod(); // GET, POST, HEAD, PUT
```


isMethod(string $method): bool .[method]
----------------------------------------
Checks the HTTP method with which the request was made. The parameter is case-insensitive.

```php
if ($httpRequest->isMethod('GET')) // ...
```


getHeader(string $header): ?string .[method]
--------------------------------------------
Returns an HTTP header or `null` if it does not exist. The parameter is case-insensitive:

```php
$userAgent = $httpRequest->getHeader('User-Agent');
```


getHeaders(): array .[method]
-----------------------------
Returns all HTTP headers as associative array:

```php
$headers = $httpRequest->getHeaders();
echo $headers['Content-Type'];
```


getReferer(): ?Nette\Http\Url .[method]
---------------------------------------
What URL did the user come from? Beware, it is not reliable at all.


isSecured(): bool .[method]
---------------------------
Is the connection encrypted (HTTPS)? You may need to [set up a proxy|configuration#HTTP proxy] for proper functionality.


isSameSite(): bool .[method]{data-version:v2.4.10}
--------------------------------------------------
Is the request coming from the same (sub) domain and is initiated by clicking on a link? Nette uses the `nette-samesite` cookie to detect it.


isAjax(): bool .[method]
------------------------
Is it an AJAX request?


getRemoteAddress(): ?string .[method]
-------------------------------------
Returns the user's IP address. You may need to [set up a proxy|configuration#HTTP proxy] for proper functionality.


getRemoteHost(): ?string .[method]
----------------------------------
Returns DNS translation of the user's IP address. You may need to [set up a proxy|configuration#HTTP proxy] for proper functionality.


getRawBody(): ?string .[method]
-------------------------------
Returns the body of the HTTP request:

```php
$body = $httpRequest->getRawBody();
```


detectLanguage(array $langs): ?string .[method]
-----------------------------------------------
Detects language. As a parameter `$lang`, we pass an array of languages ​​that the application supports, and it returns the one preferred by browser. It is not magic, the method just uses the `Accept-Language` header. If no match is reached, it returns `null`.

```php
// Header sent by browser: Accept-Language: cs,en-us;q=0.8,en;q=0.5,sl;q=0.3

$langs = ['hu', 'pl', 'en']; // languages supported in application
echo $httpRequest->detectLanguage($langs); // en
```


RequestFactory
==============

The object of the current HTTP request is created by [api:Nette\Http\RequestFactory]. If you are writing an application that does not use a DI container, you create a request as follows:

```php
$factory = new Nette\Http\RequestFactory;
$httpRequest = $factory->createHttpRequest();
```

RequestFactory can be configured before calling `createHttpRequest()`. We can disable all sanitization of input parameters from invalid UTF-8 sequences using `$factory->setBinary()`. And also set up a proxy server, which is important for the correct detection of the user's IP address using `$factory->setProxy(...)`.

It's possible to clean up URLs from characters that can get into them because of poorly implemented comment systems on various other websites by using filters:

```php
// remove spaces from path
$requestFactory->urlFilters['path']['%20'] = '';

// remove dot, comma or right parenthesis form the end of the URL
$requestFactory->urlFilters['url']['[.,)]$'] = '';

// clean the path from duplicated slashes (default filter)
$requestFactory->urlFilters['path']['/{2,}'] = '/';
```


Uploaded Files
==============

Method `Nette\Http\Request::getFiles()` return a tree of upload files in a normalized structure, with each leaf an instance of [api:Nette\Http\FileUpload]. These objects encapsulate the data submitted by the `<input type=file>` form element.

The structure reflects the naming of elements in HTML. In the simplest example, this might be a single named form element submitted as:

```latte
<input type="file" name="avatar">
```

In this case, the `$request->getFiles()` returns array:

```php
[
	'avatar' => /* FileUpload instance */
]
```

The `FileUpload` object is created even if the user did not upload any file or the upload failed. Method `hasFile()` returns true if a file has been sent:

```php
$request->getFile('avatar')->hasFile();
```

In the case of an input using array notation for the name:

```latte
<input type="file" name="my-form[details][avatar]">
```

returned tree ends up looking like this:

```php
[
	'my-form' => [
		'details' => [
			'avatar' => /* FileUpload instance */
		],
	],
]
```

You can also create arrays of files:

```latte
<input type="file" name="my-form[details][avatars][] multiple">
```

In such a case structure looks like:

```php
[
	'my-form' => [
		'details' => [
			'avatars' => [
				0 => /* FileUpload instance */,
				1 => /* FileUpload instance */,
				2 => /* FileUpload instance */,
			],
		],
	],
]
```

The best way to access index 1 of a nested array is as follows:

```php
$file = Nette\Utils\Arrays::get(
	$request->getFiles(),
	['my-form', 'details', 'avatars', 1],
	null
);
if ($file instanceof FileUpload) {
	// ...
}
```

Because you can't trust data from the outside and therefore don't rely on the form of the file structure, it's safer to use the [Arrays::get()|utils:arrays#get()] than the `$request->getFiles()['my-form']['details']['avatars'][1]`, which may fail.


Overview of `FileUpload` Methods .{toc: FileUpload}
---------------------------------------------------


hasFile(): bool .[method]
-------------------------
Returns `true` if the user has uploaded a file.


isOk(): bool .[method]
----------------------
Returns `true` if the file was uploaded successfully.


getError(): int .[method]
-------------------------
Returns the error code associated with the uploaded file. It is be one of [UPLOAD_ERR_XXX|http://php.net/manual/en/features.file-upload.errors.php] constants. If the file was uploaded successfully, it returns `UPLOAD_ERR_OK`.


move(string $dest) .[method]
----------------------------
Moves an uploaded file to a new location. If the destination file already exists, it will be overwritten.

```php
$file->move('/path/to/files/name.ext');
```


getContents(): ?string .[method]
--------------------------------
Returns the contents of the uploaded file. If the upload was not successful, it returns `null`.


getContentType(): ?string .[method]
-----------------------------------
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`.

.[caution]
Requires PHP extension `fileinfo`.


getName(): string .[method]
---------------------------
Returns the original file name as submitted by the browser.

.[caution]
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 .[method]
------------------------------------
Returns the sanitized file name. The resulting name contains only ASCII characters `[a-zA-Z0-9.-]`.


getSize(): int .[method]
------------------------
Returns the size of the uploaded file. If the upload was not successful, it returns `0`.


getTemporaryFile(): string .[method]
------------------------------------
Returns the path of the temporary location of the uploaded file. If the upload was not successful, it returns `''`.


isImage(): bool .[method]
-------------------------
Returns `true` if the uploaded file is a JPEG, PNG, or GIF image. Detection is based on its signature. The integrity of the entire file is not checked. You can find out if an image is not corrupted for example by trying to [load it|#toImage].

.[caution]
Requires PHP extension `fileinfo`.


getImageSize(): ?array .[method]
--------------------------------
Returns a pair of `[width, height]` with dimensions of the uploaded image. If the upload was not successful or is not a valid image, it returns `null`.


toImage(): Nette\Utils\Image .[method]
--------------------------------------
Loads an image as an [Image|utils:images] object. If the upload was not successful or is not a valid image, it throws an `Nette\Utils\ImageException` exception.

HTTP Request

Nette encapsulates the HTTP request into objects with an understandable API while providing a sanitization filter.

Installation:

composer require nette/http

An HTTP request is an Nette\Http\Request object, which you get by passing it using dependency injection. In presenters simply call $httpRequest = $this->getHttpRequest().

What is important is that Nette when creating this object, it clears all GET, POST and COOKIE input parameters as well as URLs of control characters and invalid UTF-8 sequences. So you can safely continue working with the data. The cleaned data is then used in presenters and forms.

Nette\Http\Request

This class is immutable, ie. it has no setters.

getUrl(): Nette\Http\UrlScript

Returns the URL of the request as object UrlScript.

$url = $httpRequest->getUrl();
echo $url; // https://nette.org/en/documentation?action=edit
echo $url->getHost(); // nette.org

Browsers do not send a fragment to the server, so $url->getFragment() will return an empty string.

getQuery(string $key=null, $default=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, $default=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 $key): Nette\Http\FileUpload|array|null

Returns upload as object Nette\Http\FileUpload:

$file = $httpRequest->getFile('avatar');
if ($file->hasFile()) { // was any file uploaded?
	$file->getName(); // name of the file sent by user
	$file->getSanitizedName(); // the name without dangerous characters
}

getFiles(): array

Returns tree of upload files in a normalized structure, with each leaf an instance of Nette\Http\FileUpload:

$files = $httpRequest->getFiles();

getCookie(string $key, $default=null): string|array|null

Returns a cookie or null if it does not exist.

$sessId = $httpRequest->getCookie('sess_id');

getCookies(): array

Returns all cookies:

$cookies = $httpRequest->getCookies();

getMethod(): string

Returns the HTTP method with which the request was made.

echo $httpRequest->getMethod(); // GET, POST, HEAD, PUT

isMethod(string $method)bool

Checks the HTTP method with which the request was made. The parameter is case-insensitive.

if ($httpRequest->isMethod('GET')) // ...

getHeader(string $header): ?string

Returns an HTTP header or null if it does not exist. The parameter is case-insensitive:

$userAgent = $httpRequest->getHeader('User-Agent');

getHeaders(): array

Returns all HTTP headers as associative array:

$headers = $httpRequest->getHeaders();
echo $headers['Content-Type'];

getReferer(): ?Nette\Http\Url

What URL did the user come from? Beware, it is not reliable at all.

isSecured(): bool

Is the connection encrypted (HTTPS)? You may need to set up a proxy for proper functionality.

isSameSite(): bool

Is the request coming from the same (sub) domain and is initiated by clicking on a link? Nette uses the nette-samesite cookie to detect it.

isAjax(): bool

Is it an AJAX request?

getRemoteAddress(): ?string

Returns the user's IP address. You may need to set up a proxy for proper functionality.

getRemoteHost(): ?string

Returns DNS translation of the user's IP address. You may need to set up a proxy for proper functionality.

getRawBody(): ?string

Returns the body of the HTTP request:

$body = $httpRequest->getRawBody();

detectLanguage(array $langs): ?string

Detects language. As a parameter $lang, we pass an array of languages ​​that the application supports, and it returns the one preferred by browser. It is not magic, the method just uses the Accept-Language header. If no match is reached, it returns null.

// Header sent by browser: Accept-Language: cs,en-us;q=0.8,en;q=0.5,sl;q=0.3

$langs = ['hu', 'pl', 'en']; // languages supported in application
echo $httpRequest->detectLanguage($langs); // en

RequestFactory

The object of the current HTTP request is created by Nette\Http\RequestFactory. If you are writing an application that does not use a DI container, you create a request as follows:

$factory = new Nette\Http\RequestFactory;
$httpRequest = $factory->createHttpRequest();

RequestFactory can be configured before calling createHttpRequest(). We can disable all sanitization of input parameters from invalid UTF-8 sequences using $factory->setBinary(). And also set up a proxy server, which is important for the correct detection of the user's IP address using $factory->setProxy(...).

It's possible to clean up URLs from characters that can get into them because of poorly implemented comment systems on various other websites by using filters:

// remove spaces from path
$requestFactory->urlFilters['path']['%20'] = '';

// remove dot, comma or right parenthesis form the end of the URL
$requestFactory->urlFilters['url']['[.,)]$'] = '';

// clean the path from duplicated slashes (default filter)
$requestFactory->urlFilters['path']['/{2,}'] = '/';

Uploaded Files

Method Nette\Http\Request::getFiles() return a tree of upload files in a normalized structure, with each leaf an instance of Nette\Http\FileUpload. These objects encapsulate the data submitted by the <input type=file> form element.

The structure reflects the naming of elements in HTML. In the simplest example, this might be a single named form element submitted as:

<input type="file" name="avatar">

In this case, the $request->getFiles() returns array:

[
	'avatar' => /* FileUpload instance */
]

The FileUpload object is created even if the user did not upload any file or the upload failed. Method hasFile() returns true if a file has been sent:

$request->getFile('avatar')->hasFile();

In the case of an input using array notation for the name:

<input type="file" name="my-form[details][avatar]">

returned tree ends up looking 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 structure looks like:

[
	'my-form' => [
		'details' => [
			'avatars' => [
				0 => /* FileUpload instance */,
				1 => /* FileUpload instance */,
				2 => /* FileUpload instance */,
			],
		],
	],
]

The best way to access index 1 of a nested array is as follows:

$file = Nette\Utils\Arrays::get(
	$request->getFiles(),
	['my-form', 'details', 'avatars', 1],
	null
);
if ($file instanceof FileUpload) {
	// ...
}

Because you can't trust data from the outside and therefore don't rely on the form of the file structure, it's safer to use the Arrays::get() than the $request->getFiles()['my-form']['details']['avatars'][1], which may fail.

Overview of FileUpload Methods

hasFile(): bool

Returns true if the user has 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 be one of 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 PHP extension fileinfo.

getName(): 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. The resulting name contains only ASCII characters [a-zA-Z0-9.-].

getSize(): int

Returns the size of the uploaded file. If the upload was not successful, it returns 0.

getTemporaryFile(): string

Returns the path of 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, or GIF image. Detection is based on its signature. The integrity of the entire file is not checked. You can find out if an image is not corrupted for example by trying to load it.

Requires PHP extension fileinfo.

getImageSize(): ?array

Returns a pair of [width, height] with dimensions of the uploaded image. If the upload was not successful or is not a valid image, it returns null.

toImage(): Nette\Utils\Image

Loads an image as an Image object. If the upload was not successful or is not a valid image, it throws an Nette\Utils\ImageException exception.