Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 62 ยท Routing and Controllers

The Request Object

Learn the Symfony Request object - query and request bags, headers, cookies, files, attributes, JSON bodies, client IP, trusted proxies and content negotiation.

PHP hands you the incoming request as a loose collection of global arrays: $_GET, $_POST, $_COOKIE, $_FILES and $_SERVER. They are always available, they can be changed from anywhere, and they are awkward to test. Symfony's HttpFoundation component wraps all of them in one immutable-by-convention object, Symfony\Component\HttpFoundation\Request, built once by the front controller and passed to your controller.

This lesson tours that object: the parameter bags for query string, form data, cookies and files; headers; request attributes; JSON bodies; the client's IP address; and content negotiation. The real API is shown in read-only blocks. The runnable parts are a small stand-in Request built from simulated superglobals, so you can see why the bags exist and how headers and negotiation work under the hood.

One object, several bags

Each group of data lives in a bag, an object with consistent methods:

Property Source Example
$request->query Query string ($_GET) ?page=2
$request->request Form body ($_POST) a submitted HTML form
$request->cookies Cookies theme=dark
$request->files Uploads ($_FILES) avatar
$request->headers HTTP headers User-Agent
$request->attributes Data added by Symfony _route, route placeholders
$request->server Server variables ($_SERVER) REMOTE_ADDR
PHP
// real Symfony, read-only
public function search(Request $request): Response
{
    $term = $request->query->get('q', '');            // string, with a default
    $page = $request->query->getInt('page', 1);        // cast to int, default 1
    $debug = $request->query->getBoolean('debug');     // "1", "true", "on" and "yes" are true

    $name = $request->request->get('name');            // value of a POST field
    $theme = $request->cookies->get('theme', 'light');
    $agent = $request->headers->get('User-Agent');
    $route = $request->attributes->get('_route');      // name of the matched route
    // ...
}

The typed getters (getInt(), getBoolean(), and others such as getEnum()) are worth using: they turn the raw strings from the URL into the types your code expects and never emit an "Undefined array key" warning. Two details to remember. First, get() only returns scalar values or null; for array parameters like ?ids[]=1&ids[]=2 use $request->query->all('ids'). Second, $request->request only contains form-encoded bodies, so a JSON body appears nowhere in it (more on that below).

flowchart TB
    G["PHP superglobals<br/>$_GET, $_POST, $_COOKIE, $_FILES, $_SERVER"] --> F["Request::createFromGlobals()<br/>(in public/index.php)"]
    F --> R["Request object"]
    R --> Q["query"]
    R --> B["request"]
    R --> C["cookies"]
    R --> FI["files"]
    R --> H["headers"]
    R --> A["attributes<br/>(route, placeholders)"]
    R --> S["server"]
    R --> CTRL["Your controller"]

The front controller builds the Request once from the superglobals; controllers only ever see the object and its bags.

A Request stand-in

Because a Request is plain data, you can build one by hand, which is what tests do. The stand-in below takes simulated superglobals, extracts headers from HTTP_* server keys the way PHP exposes them, and offers typed getters.

PHP A Request built from simulated superglobals (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Try changing page to 'abc': getInt() quietly returns 0 instead of failing. In real code you would validate such input, which later lessons cover.

Headers and attributes

$request->headers is case-insensitive, as HTTP requires: get('user-agent') and get('User-Agent') return the same value, as the output above shows. Always read headers through the bag instead of $_SERVER.

$request->attributes is different. It is not user input. It is where Symfony and your code stash information about the request as it travels through the kernel: the matched route name (_route), the route parameters, and the controller to call. The route placeholders you saw in Route Parameters and Requirements are attributes, which is why controller arguments can be resolved from them. You can add your own, for example in a listener that stores the current tenant.

Reading the body

For a form submission, read $request->request->get('field'). For JSON APIs, the body is raw text, and Symfony gives you helpers:

PHP
// real Symfony, read-only
$raw = $request->getContent();      // the body as a string
$data = $request->toArray();        // decoded JSON as an array; invalid JSON becomes a 400 response
$payload = $request->getPayload();  // an InputBag: the form fields OR the decoded JSON body
$title = $payload->getString('title');

In larger applications you rarely decode by hand: Mapping Request Data to Objects shows how #[MapRequestPayload] converts the body into a validated object.

Uploaded files are in $request->files, which holds UploadedFile objects (or null); the dedicated upload lesson covers moving and validating them.

Client IP and trusted proxies

$request->getClientIp() returns the visitor's address, and it is a good example of why a framework helps. Behind a load balancer or CDN, REMOTE_ADDR is the proxy's address, and the real visitor is in the X-Forwarded-For header. But any visitor can send that header, so trusting it blindly lets people forge their IP. Symfony only trusts forwarded headers when the connection comes from a proxy you declared:

YAML
# config/packages/framework.yaml (real Symfony, read-only)
framework:
    trusted_proxies: '%env(TRUSTED_PROXIES)%'     # e.g. "10.0.0.0/8,127.0.0.1"
    trusted_headers: ['x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-forwarded-port']

The same setting makes isSecure() and getSchemeAndHttpHost() report https when TLS ends at the proxy, which is vital for generating correct absolute URLs. Without it, apps behind HTTPS proxies often produce http:// links.

Content negotiation

Clients say what they want with headers such as Accept and Accept-Language. Each entry may carry a quality value q between 0 and 1. The helpers on the real Request do the parsing:

PHP
// real Symfony, read-only
$format = $request->getPreferredFormat('html');             // "json", "html", ... based on Accept
$language = $request->getPreferredLanguage(['en', 'fr']);   // best match from your supported list
$types = $request->getAcceptableContentTypes();             // all accepted types, best first

The stand-in below parses Accept with q weights, resolves client IPs with and without a trusted proxy, and decodes JSON bodies strictly.

PHP Negotiation, trusted proxies and JSON bodies (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two lessons hide in that output. A forged X-Forwarded-For is ignored unless the connection really came through a trusted proxy, and even then the stand-in walks the chain from the right, so entries the client invented on the left are not believed.

Creating requests in tests

Because a request is just an object, tests create one without a web server. The real component offers Request::create('/search', 'GET', ['q' => 'symfony']), and Request::createFromGlobals() is what public/index.php calls for real traffic. You will use create() heavily in the testing lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which bag holds the values of a submitted HTML form (a POST body)?

    query is the query string ($_GET) and request is the form body ($_POST). attributes holds data added by Symfony, such as route parameters.
  2. 2. Why does $request->query->getInt('page', 1) beat reading $_GET['page'] directly?

    Typed getters cast the raw string and apply a default, avoiding warnings and manual casting.
  3. 3. When is it safe for getClientIp() to use the X-Forwarded-For header?

    Any client can send X-Forwarded-For. Symfony only believes it when the immediate connection comes from a trusted proxy.
  4. 4. A client sends a JSON body. Where will you NOT find its fields?

    JSON is not form-encoded, so $request->request stays empty. Use getContent(), toArray() or getPayload().

Summary

  • Request wraps the superglobals in bags: query, request, cookies, files, headers, attributes and server.
  • Use typed getters like getInt() and getBoolean() with defaults; use all('key') for arrays.
  • Headers are case-insensitive; attributes carries route data and your own per-request values.
  • JSON bodies come from getContent(), toArray() or getPayload(), not from $request->request.
  • Configure trusted_proxies and trusted_headers behind a proxy so client IP and scheme are right, and use getPreferredFormat() and getPreferredLanguage() for negotiation.

Next up: Responses, JSON and Redirects.