Http
π Abstraction for HTTP request, response and session. Provides careful data sanitization and utility for URL and cookies manipulation.
Install / Use
/learn @nette/HttpREADME
Nette HTTP Component
Introduction
HTTP request and response are encapsulated in Nette\Http\Request and Nette\Http\Response objects which offer comfortable API and also act as
sanitization filter.
Documentation can be found on the website.
Support Me
Do you like Nette DI? Are you looking forward to the new features?
Thank you!
Installation
composer require nette/http
It requires PHP version 8.2 and supports PHP up to 8.5.
HTTP Request
An HTTP request is an Nette\Http\Request object. 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.
Class Request 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 a 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 object [UrlScript|urls#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): 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 $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): 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\UrlImmutable
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|configuring#HTTP proxy] for proper functionality.
isSameSite(): bool
Is the request coming from the same (sub) domain and is initiated by clicking on a link?
isAjax(): bool
Is it an AJAX request?
getRemoteAddress(): ?string
Returns the user's IP address. You may need to [set up a proxy|configuring#HTTP 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->fromGlobals();
RequestFactory can be configured before calling fromGlobals(). 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,}'] = '/';
HTTP Response
An HTTP response is an Nette\Http\Response object. Unlike the Request, the object is mutable, so you can use setters to change the state, ie to send headers. Remember that all setters must be called before any actual output is sent. The isSent() method tells if output have been sent. If it returns true, each attempt to send a header throws an Nette\InvalidStateException exception.
setCode(int $code, string $reason = null)
Changes a status response code. For better source code readability it is recommended to use predefined constants instead of actual numbers.
$httpResponse->setCode(Nette\Http\Response::S404_NotFound);
getCode(): int
Returns the status code of the response.
isSent(): bool
Returns whether headers have already been sent from the server to the browser, so it is no longer possible to send headers or change the status code.
setHeader(string $name, string $value)
Sends an HTTP header and overwrites previously sent header of the same name.
$httpResponse->setHeader('Pragma', 'no-cache');
addHeader(string $name, string $value)
Sends an HTTP header and doesn't overwrite previously sent header of the same name.
$httpResponse->addHeader('Accept', 'application/json');
$httpResponse->addHeader('Accept', 'application/xml');
deleteHeader(string $name)
Deletes a previously sent HTTP header.
getHeader(string $header): ?string
Returns the sent HTTP header, or null if it does not exist. The parameter is case-insensitive.
$pragma = $httpResponse->getHeader('Pragma');
getHeaders(): array
Returns all sent HTTP headers as associative array.
$headers = $httpResponse->getHeaders();
echo $headers['Pragma'];
setContentType(string $type, string $charset = null)
Sends the header Content-Type.
$httpResponse->setContentType('text/plain', 'UTF-8');
