Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 62 ยท Routing and Controllers

Responses, JSON and Redirects

Learn Symfony responses - Response, JsonResponse, RedirectResponse, BinaryFileResponse and StreamedResponse, status codes, headers, cookies and caching.

Every controller ends the same way: by returning a Response. A response is the HTTP answer in object form: a status code, a set of headers and a body. Symfony's HttpFoundation component provides the base Response class and specialized subclasses for the jobs you meet again and again: sending JSON, redirecting, downloading a file and streaming a large body.

This lesson explains each of them, shows how to choose a sensible status code, and covers headers, cookies and cache headers. The real Symfony code is read-only. The runnable stand-ins are tiny response classes that render the raw HTTP text, which is a good way to see that a response really is just a status line, some headers and a body.

The Response class

PHP
// real Symfony, read-only
use Symfony\Component\HttpFoundation\Response;

$response = new Response('<h1>Hello</h1>', Response::HTTP_OK, ['Content-Type' => 'text/html']);

$response->setStatusCode(Response::HTTP_CREATED);   // 201
$response->headers->set('X-Request-Id', 'abc123');
$response->setContent('<h1>Created</h1>');

Constants such as Response::HTTP_NOT_FOUND make code more readable than bare numbers. Notice that nothing is sent when you create the object. The kernel sends the response after your controller returns, and listeners can still adjust it on the way out; this is what makes features like the profiler toolbar, cache headers and cookies work.

flowchart LR
    C["Controller returns<br/>Response object"] --> L["Kernel listeners<br/>(may add headers, cookies)"]
    L --> P["Response::prepare()<br/>(content type, length, ...)"]
    P --> S["send()<br/>status, headers, body"]
    S --> B["Browser"]

A response is a plain object until the very end of the request, when it is prepared and sent in one go.

Choosing a status code

The status code is part of your API. Use the one that says what happened:

Code Name Use it when
200 OK A normal successful read
201 Created A resource was created; add a Location header
204 No Content Success with nothing to return, such as a delete
301 / 302 Moved Permanently / Found Redirects (permanent / temporary)
304 Not Modified The client's cached copy is still valid
400 Bad Request Malformed input, such as invalid JSON
401 / 403 Unauthorized / Forbidden Not logged in / not allowed
404 Not Found The resource does not exist
422 Unprocessable Content Well-formed input that fails validation
500 Internal Server Error A bug; Symfony sends this for uncaught exceptions

For errors you usually do not build a response by hand. Throw NotFoundHttpException, AccessDeniedHttpException or the general HttpException and Symfony's error handling turns the exception into a response with the right status, an HTML page in a browser and a JSON structure for API clients.

Response subclasses in practice

JSON. JsonResponse encodes an array (or any JSON-serializable value) and sets Content-Type: application/json. In a controller the json() helper is the shortcut:

PHP
// real Symfony, read-only
return $this->json(['id' => 7, 'title' => 'Hello'], Response::HTTP_CREATED, ['Location' => '/api/posts/7']);
// the same, without the helper:
return new JsonResponse(['id' => 7, 'title' => 'Hello'], 201, ['Location' => '/api/posts/7']);

When the Serializer component is installed, $this->json() uses it, so objects and serialization groups work. Without it, it falls back to json_encode. Section "APIs" later in the tutorial covers this in depth.

Redirects. RedirectResponse sets a Location header and a 3xx status (302 by default):

PHP
// real Symfony, read-only
return $this->redirectToRoute('post_show', ['id' => $post->getId()]);          // 302
return $this->redirectToRoute('blog_index', [], Response::HTTP_MOVED_PERMANENTLY); // 301
return $this->redirect('https://example.com/elsewhere');

The redirect-after-POST pattern is the standard way to handle form submissions: process the form, then redirect to a page that shows the result, so refreshing the browser does not resubmit the form.

Never pass an unchecked, user-supplied URL to redirect(), for example $this->redirect($request->query->get('next')). That is an open redirect: attackers craft links on your domain that send victims to their site. Redirect to named routes, or validate that the target is a local path first.

Files. BinaryFileResponse serves a file from disk efficiently and handles range requests and the Content-Disposition header. The file() helper wraps it:

PHP
// real Symfony, read-only
return $this->file($path, 'invoice-2025.pdf');   // download; use ResponseHeaderBag::DISPOSITION_INLINE to display in the browser

Streaming. StreamedResponse takes a callback that echoes the body in pieces, so a large export never has to sit in memory:

PHP
// real Symfony, read-only
return new StreamedResponse(function () use ($rows): void {
    foreach ($rows as $row) {
        echo implode(',', $row), "\n";
        flush();
    }
}, 200, ['Content-Type' => 'text/csv']);

Rendering responses as raw HTTP

The next stand-in has a base Response and the three subclasses JsonResponse, RedirectResponse and an empty 204 helper, plus a method that renders the exact text a server would send. It is a model of the idea, not Symfony's source.

PHP Responses as plain objects (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.

Look at how little there is: a redirect is only a status and a Location header with an empty body, and a 204 has neither a content type nor a body.

Headers, cookies and caching

On the real Response, headers live in $response->headers, a bag like the one on the request. Cookies are created with the Cookie class and attached to the headers, and Symfony turns them into Set-Cookie lines:

PHP
// real Symfony, read-only
use Symfony\Component\HttpFoundation\Cookie;

$response->headers->setCookie(Cookie::create('theme', 'dark')->withExpires(new \DateTimeImmutable('+30 days')));
$response->headers->set('X-Frame-Options', 'DENY');

For caching, the response has helpers that write correct Cache-Control and validator headers:

PHP
// real Symfony, read-only
$response->setPublic();          // shared caches such as a CDN may store it
$response->setMaxAge(600);       // browsers: 10 minutes
$response->setSharedMaxAge(3600); // CDNs and reverse proxies: 1 hour
$response->setEtag(md5($content));

if ($response->isNotModified($request)) {
    return $response;            // becomes a 304 with an empty body
}

A later lesson on HTTP caching builds on this. One rule to remember now: a response that depends on the logged-in user or on a session must not be public.

Streaming and downloads

Two details matter for large or generated output. A streamed response never holds the full body, so it keeps memory use flat for huge exports. And downloads need a safe Content-Disposition header, including for file names with accents. Symfony handles the encoding for you (HeaderUtils::makeDisposition() underneath file()), but the stand-in below shows what it has to do: send a plain ASCII fallback name together with a percent-encoded UTF-8 one.

PHP A streamed CSV download (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.

The callback ran only inside send(), and each row was echoed as soon as the generator produced it. That is the whole trick: with a database cursor in place of the generator, a million-row export uses the same memory as a ten-row one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When is a Symfony Response actually sent to the browser?

    A Response is an object until the end of the request. The kernel lets listeners adjust it, prepares it and then sends it.
  2. 2. Which status code fits a successful DELETE that returns no body?

    204 says the request succeeded and there is nothing to return.
  3. 3. Why is $this->redirect($request->query->get('next')) dangerous?

    Unvalidated redirect targets are a security hole. Redirect to named routes or validate that the path is local.
  4. 4. What is the main benefit of StreamedResponse for a huge CSV export?

    The callback echoes rows as they are produced, so the full export never has to be held in memory.
  5. 5. Which helper turns a form POST into a safe 'redirect after POST' flow?

    After processing a form, redirectToRoute() sends the browser to a result page so a refresh does not resubmit the form.

Summary

  • A Response is a status, headers and a body held in an object; the kernel sends it after your controller (and listeners) are done.
  • Choose meaningful status codes: 201 for creation, 204 for no body, 3xx for redirects, 4xx for client errors, and throw HttpException subclasses for errors.
  • JsonResponse / $this->json(), RedirectResponse / redirectToRoute(), BinaryFileResponse / file() and StreamedResponse cover the common cases.
  • Never redirect to an unchecked user-supplied URL.
  • Use the response helpers for cookies and cache headers, and keep user-specific responses out of public caches.

Next up: Mapping Request Data to Objects.