Lets say we want to build a paginated list of products, where the number of the page is passed as a query string parameter. For instance, to fetch the 3rd page, you'd go to:
http://example.com/products?page=3
The raw HTTP request would look something like this:
GET /products?page=3 HTTP/1.1
Host: example.com
Accept: text/html
User-Agent: Mozilla/5.0 (Macintosh)
In order to get the page number from the request object, you can access the query
property:
$page = $request->query->get('page'); // 3
In the case of a page
parameter, you will probably want to pass a default value in case the query string parameter is not set:
$page = $request->query->get('page', 1);
This means that when someone visits http://example.com/products (note the absence of the query string), the $page
variable will contain the default value 1
.
PHP exposes a number of so-called global variables which contain information about the HTTP request, such as $_POST
, $_GET
, $_FILES
, $_SESSION
, etc. The Request
class contains a static createFromGlobals()
method in order to instantiate a request object based on these variables:
use Symfony\Component\HttpFoundation\Request;
$request = Request::createFromGlobals();
When using the Symfony framework, you should not instantiate the request object yourself. Instead, you should use the object that is instantiated when the framework is bootstrapped in app.php
/ app_dev.php
. For instance by type hinting the request object in your controller.
To get the contents of a form that is submitted with method="post"
, use the post
property:
$name = $request->request->get('name');
$id = $request->cookies->get('PHPSESSID');
This will return the value of the 'PHPSESSID' cookie sent by the browser.