If you install this component outside of a Symfony application, you must
require the vendor/autoload.php file in your code to enable the class
autoloading mechanism provided by Composer. Read
this article for more details.

This article explains how to use the HttpFoundation features as an
independent component in any PHP application. In Symfony applications
everything is already configured and ready to use. Read the Controller
article to learn about how to use these features when creating controllers.

When PHP imports the request query, it handles request parameters like
foo[bar]=baz in a special way as it creates an array. So you can get the
foo parameter and you will get back an array with a bar element:

Thanks to the public attributes property, you can store additional data
in the request, which is also an instance of
ParameterBag. This is mostly used
to attach information that belongs to the Request and that needs to be
accessed from many different points in your application.

Finally, the raw data sent with the request body can be accessed using
getContent():

$content=$request->getContent();

For instance, this may be useful to process a JSON string sent to the
application by a remote service using the HTTP POST method.

Instead of creating a request based on the PHP globals, you can also simulate
a request:

1
2
3
4
5

$request=Request::create('/hello-world','GET',['name'=>'Fabien']);

The create() method
creates a request based on a URI, a method and some parameters (the
query parameters or the request ones depending on the HTTP method); and of
course, you can also override all other variables as well (by default, Symfony
creates sensible defaults for all the PHP global variables).

Based on such a request, you can override the PHP global variables via
overrideGlobals():

$request->overrideGlobals();

Tip

You can also duplicate an existing request via
duplicate() or
change a bunch of parameters with a single call to
initialize().

If you have a session attached to the request, you can access it via the
getSession() method;
the
hasPreviousSession()
method tells you if the request contains a session which was started in one of
the previous requests.

Processing HTTP headers is not a trivial task because of the escaping and white
space handling of their contents. Symfony provides a
HeaderUtils class that abstracts
this complexity and defines some methods for the most common tasks:

An increasingly common need for applications to comply with user protection
regulations is to anonymize IP addresses before logging and storing them for
analysis purposes. Use the anonymize() method from the
IpUtils to do that:

The Request class should not be overridden as it is a data object that
represents an HTTP message. But when moving from a legacy system, adding
methods or changing some default behavior might help. In that case, register a
PHP callable that is able to create an instance of your Request class:

A Response object holds all the
information that needs to be sent back to the client from a given request. The
constructor takes up to three arguments: the response content, the status
code, and an array of HTTP headers:

In addition to the Cookie::create() method, you can create a Cookie
object from a raw header value using fromString()
method. You can also use the with*() methods to change some Cookie property (or
to build the entire Cookie using a fluent interface). Each with*() method returns
a new object with the modified property:

The flush() function does not flush buffering. If ob_start() has
been called before or the output_bufferingphp.ini option is enabled,
you must call ob_flush() before flush().

Additionally, PHP isn't the only layer that can buffer output. Your web
server might also buffer based on its configuration. Some servers, such as
nginx, let you disable buffering at the config level or by adding a special HTTP
header in the response:

// disables FastCGI buffering in nginx only for this response$response->headers->set('X-Accel-Buffering','no')

When sending a file, you must add a Content-Disposition header to your
response. While creating this header for basic file downloads is straightforward,
using non-ASCII filenames is more involved. The
makeDisposition()
abstracts the hard work behind a simple API:

The BinaryFileResponse will automatically handle Range and
If-Range headers from the request. It also supports X-Sendfile
(see for nginx and Apache). To make use of it, you need to determine
whether or not the X-Sendfile-Type header should be trusted and call
trustXSendfileTypeHeader()
if it should:

BinaryFileResponse::trustXSendfileTypeHeader();

Note

The BinaryFileResponse will only handle X-Sendfile if the particular header is present.
For Apache, this is not the default case.

To add the header use the mod_headers Apache module and add the following to the Apache configuration:

1
2
3
4
5
6
7
8
9
10

<IfModulemod_xsendfile.c># This is already present somewhere...XSendFileonXSendFilePath ...some path...
# This needs to be added:<IfModulemod_headers.c>RequestHeader set X-Sendfile-Type X-Sendfile
</IfModule></IfModule>

With the BinaryFileResponse, you can still set the Content-Type of the sent file,
or change its Content-Disposition:

It is possible to delete the file after the request is sent with the
deleteFileAfterSend() method.
Please note that this will not work when the X-Sendfile header is set.

If the size of the served file is unknown (e.g. because it's being generated on the fly,
or because a PHP stream filter is registered on it, etc.), you can pass a Stream
instance to BinaryFileResponse. This will disable Range and Content-Length
handling, switching to chunked encoding instead:

If you just created the file during this same request, the file may be sent
without any content. This may be due to cached file stats that return zero for
the size of the file. To fix this issue, call clearstatcache(true, $file)
with the path to the binary file.

There is also a helpful JsonResponse
class, which can make this even easier:

1
2
3
4
5
6
7
8
9
10
11
12

useSymfony\Component\HttpFoundation\JsonResponse;// if you know the data to send when creating the response$response=newJsonResponse(['data'=>123]);// if you don't know the data to send when creating the response$response=newJsonResponse();// ...$response->setData(['data'=>123]);// if the data to send is already encoded in JSON$response=JsonResponse::fromJsonString('{ "data": 123 }');

The JsonResponse class sets the Content-Type header to
application/json and encodes your data to JSON when needed.

Caution

To avoid XSSI JSON Hijacking, you should pass an associative array
as the outer-most array to JsonResponse and not an indexed array so
that the final result is an object (e.g. {"object": "not inside an array"})
instead of an array (e.g. [{"object": "inside an array"}]). Read
the OWASP guidelines for more information.

Only methods that respond to GET requests are vulnerable to XSSI 'JSON Hijacking'.
Methods responding to POST requests only remain unaffected.

Some web sites have a "safe" mode to assist those who don't want to be exposed
to content to which they might object. The RFC 8674 specification defines a
way for user agents to ask for safe content to a server.

The specification does not define what content might be considered objectionable,
so the concept of "safe" is not precisely defined. Rather, the term is interpreted
by the server and within the scope of each web site that chooses to act upon this information.