HTTP Request & Response

HTTP request and response are encapsulated in Nette\Http\Request and Response objects which offer comfortable API and also act as sanitization filter.

HTTP Request

Nette Framework cleans out data sent by user from control and invalid characters. It also removes any magic_quotes.

HTTP request which is an object of class Nette\Http\Request we don't create directly, but we receive it as a service from a DI container.

$httpRequest = $container->getByType('Nette\Http\Request');

The URL of the request is available as Nette\Http\UrlScript instance:

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

Determine current HTTP method:

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

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

Is the connection encrypted (HTTPS)?

echo $httpRequest->isSecured() ? 'yes' : 'no';

Is this an AJAX request?

echo $httpRequest->isAjax() ? 'yes' : 'no';

What is the user's IP address?

echo $httpRequest->getRemoteAddress(); // user's IP address
echo $httpRequest->getRemoteHost();    // and its DNS translation

What URL the user came from? Returned as Nette\Http\Url object.

echo $httpRequest->getReferer()->host;

Request parameters:

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

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

$cookies = $httpRequest->getCookies(); // array of all cookies
$sessId = $httpRequest->getCookie('sess_id'); // returns the cookie (or NULL)

Uploaded files are encapsulated into Nette\Http\FileUpload objects:

$files = $httpRequest->getFiles(); // array of all uploaded files

$file = $httpRequest->getFile('avatar'); // returns one file
echo $file->getName(); // name of the file sent by user
echo $file->getSanitizedName(); // the name without dangerous characters

HTTP headers are also accessible:

// returns associative array of HTTP headers
$headers = $httpRequest->getHeaders();

// returns concrete header (case-insensitive)
$userAgent = $httpRequest->getHeader('User-Agent');

A useful method is detectLanguage(). You can pass it an array with languages supported by application and it returns the one preferred by browser. It is not magic, the method just uses the Accept-Language header.

// 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 and URL filtering

Object holding current HTTP request is created by Nette\Http\RequstFactory. Its behavior can be modified. 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:

$requestFactory = new Nette\Http\RequestFactory;

// 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,}'] = '/';

And then we let the factory generate a new httpRequest and we store it in a system container:

// $container is a system container
$container->addService('httpRequest', $requestFactory->createHttpRequest());

HTTP response

HTTP response which is an object of class Nette\Http\Response we don't create directly, but we receive it as a service from a DI container.

$httpResponse = $container->getByType('Nette\Http\Response');

Whether it is still possible to send headers or change the status code tells the isSent() method. If it returns TRUE, it won't be possible to send another header or change the status code.

In that case, any attempt to send header or change code invokes Nette\InvalidStateException.

Response status code can be sent and retrieved this way:


echo $httpResponse->getCode(); // 404

For better source code readability it is recommended to use predefined constants instead of actual numbers:


Method setContentType($type, $charset=NULL) changes Content-Type response header:

$httpResponse->setContentType('text/plain', 'UTF-8');

Redirection to another URL is done by redirect($url, $code=302) method. Do not forget to terminate the script afterwards!


To set the document expiration date, we can use setExpiration() method. The parameter is either text data, number of seconds or a timestamp:

// browser cache expires in one hour
$httpResponse->setExpiration('+ 1 hours');

Now we send the HTTP response header:

$httpResponse->setHeader('Pragma', 'no-cache');

// or if we want to send the same header more times with different values
$httpResponse->addHeader('Pragma', 'no-cache');

Sent headers are also available:

// returns associative array of headers
$headers = $httpResponse->getHeaders();

// returns concrete header (case-insensitive)
$pragma = $httpResponse->getHeader('Pragma');

There are two methods for cookie manipulation: setCookie() and deleteCookie().

// setCookie($name, $value, $time, [$path, [$domain, [$secure, [$httpOnly]]]])
$httpResponse->setCookie('lang', 'en', '100 days'); // send cookie

// deleteCookie($name, [$path, [$domain, [$secure]]])
$httpResponse->deleteCookie('lang'); // delete cookie

These two methods can take more parameters: $path (subdirectory where the cookie will be available), $domain and $secure. Their detailed description can be found in PHP manual for setcookie function.