The HttpFoundation Component

The HttpFoundation component defines an object-oriented layer for the HTTPspecification.

In PHP, the request is represented by some global variables ($_GET,$_POST, $_FILES, $_COOKIE, $_SESSION, …) and the response isgenerated by some functions (echo, header(), setcookie(), …).

The Symfony HttpFoundation component replaces these default PHP globalvariables and functions by an object-oriented layer.

Installation

  1. $ composer require symfony/http-foundation

Note

If you install this component outside of a Symfony application, you mustrequire the vendor/autoload.php file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

This article explains how to use the HttpFoundation features as anindependent component in any PHP application. In Symfony applicationseverything is already configured and ready to use. Read the Controllerarticle to learn about how to use these features when creating controllers.

Request

The most common way to create a request is to base it on the current PHP globalvariables withcreateFromGlobals():

  1. use Symfony\Component\HttpFoundation\Request;
  2.  
  3. $request = Request::createFromGlobals();

which is almost equivalent to the more verbose, but also more flexible,__construct() call:

  1. $request = new Request(
  2. $_GET,
  3. $_POST,
  4. [],
  5. $_COOKIE,
  6. $_FILES,
  7. $_SERVER
  8. );

Accessing Request Data

A Request object holds information about the client request. This informationcan be accessed via several public properties:

  • request: equivalent of $_POST;
  • query: equivalent of $_GET ($request->query->get('name'));
  • cookies: equivalent of $_COOKIE;
  • attributes: no equivalent - used by your app to store other data (see below);
  • files: equivalent of $_FILES;
  • server: equivalent of $_SERVER;
  • headers: mostly equivalent to a subset of $_SERVER($request->headers->get('User-Agent')).Each property is a ParameterBaginstance (or a sub-class of), which is a data holder class:

  • request: ParameterBag;

  • query: ParameterBag;
  • cookies: ParameterBag;
  • attributes: ParameterBag;
  • files: FileBag;
  • server: ServerBag;
  • headers: HeaderBag.All ParameterBag instances havemethods to retrieve and update their data:

  • all()

  • Returns the parameters.
  • keys()
  • Returns the parameter keys.
  • replace()
  • Replaces the current parameters by a new set.
  • add()
  • Adds parameters.
  • get()
  • Returns a parameter by name.
  • set()
  • Sets a parameter by name.
  • has()
  • Returns true if the parameter is defined.
  • remove()
  • Removes a parameter.The ParameterBag instance alsohas some methods to filter the input values:

  • getAlpha()

  • Returns the alphabetic characters of the parameter value;
  • getAlnum()
  • Returns the alphabetic characters and digits of the parameter value;
  • getBoolean()
  • Returns the parameter value converted to boolean;
  • getDigits()
  • Returns the digits of the parameter value;
  • getInt()
  • Returns the parameter value converted to integer;
  • filter()
  • Filters the parameter by using the PHP filter_var function.All getters take up to two arguments: the first one is the parameter nameand the second one is the default value to return if the parameter does notexist:
  1. // the query string is '?foo=bar'
  2.  
  3. $request->query->get('foo');
  4. // returns 'bar'
  5.  
  6. $request->query->get('bar');
  7. // returns null
  8.  
  9. $request->query->get('bar', 'baz');
  10. // returns 'baz'

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

  1. // the query string is '?foo[bar]=baz'
  2.  
  3. $request->query->get('foo');
  4. // returns ['bar' => 'baz']
  5.  
  6. $request->query->get('foo[bar]');
  7. // returns null
  8.  
  9. $request->query->get('foo')['bar'];
  10. // returns 'baz'

Thanks to the public attributes property, you can store additional datain the request, which is also an instance ofParameterBag. This is mostly usedto attach information that belongs to the Request and that needs to beaccessed from many different points in your application.

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

  1. $content = $request->getContent();

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

Identifying a Request

In your application, you need a way to identify a request; most of the time,this is done via the "path info" of the request, which can be accessed via thegetPathInfo() method:

  1. // for a request to http://example.com/blog/index.php/post/hello-world
  2. // the path info is "/post/hello-world"
  3. $request->getPathInfo();

Simulating a Request

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

  1. $request = Request::create(
  2. '/hello-world',
  3. 'GET',
  4. ['name' => 'Fabien']
  5. );

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

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

  1. $request->overrideGlobals();

Tip

You can also duplicate an existing request viaduplicate() orchange a bunch of parameters with a single call toinitialize().

Accessing the Session

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

Processing HTTP Headers

Processing HTTP headers is not a trivial task because of the escaping and whitespace handling of their contents. Symfony provides aHeaderUtils class that abstractsthis complexity and defines some methods for the most common tasks:

  1. use Symfony\Component\HttpFoundation\HeaderUtils;
  2.  
  3. // Splits an HTTP header by one or more separators
  4. HeaderUtils::split('da, en-gb;q=0.8', ',;');
  5. // => [['da'], ['en-gb','q=0.8']]
  6.  
  7. // Combines an array of arrays into one associative array
  8. HeaderUtils::combine([['foo', 'abc'], ['bar']]);
  9. // => ['foo' => 'abc', 'bar' => true]
  10.  
  11. // Joins an associative array into a string for use in an HTTP header
  12. HeaderUtils::toString(['foo' => 'abc', 'bar' => true, 'baz' => 'a b c'], ',');
  13. // => 'foo=abc, bar, baz="a b c"'
  14.  
  15. // Encodes a string as a quoted string, if necessary
  16. HeaderUtils::quote('foo "bar"');
  17. // => '"foo \"bar\""'
  18.  
  19. // Decodes a quoted string
  20. HeaderUtils::unquote('"foo \"bar\""');
  21. // => 'foo "bar"'

Accessing Accept-* Headers Data

You can access basic data extracted from Accept-* headersby using the following methods:

  • getAcceptableContentTypes()
  • Returns the list of accepted content types ordered by descending quality.
  • getLanguages()
  • Returns the list of accepted languages ordered by descending quality.
  • getCharsets()
  • Returns the list of accepted charsets ordered by descending quality.
  • getEncodings()
  • Returns the list of accepted encodings ordered by descending quality.If you need to get full access to parsed data from Accept, Accept-Language,Accept-Charset or Accept-Encoding, you can useAcceptHeader utility class:
  1. use Symfony\Component\HttpFoundation\AcceptHeader;
  2.  
  3. $acceptHeader = AcceptHeader::fromString($request->headers->get('Accept'));
  4. if ($acceptHeader->has('text/html')) {
  5. $item = $acceptHeader->get('text/html');
  6. $charset = $item->getAttribute('charset', 'utf-8');
  7. $quality = $item->getQuality();
  8. }
  9.  
  10. // Accept header items are sorted by descending quality
  11. $acceptHeaders = AcceptHeader::fromString($request->headers->get('Accept'))
  12. ->all();

The default values that can be optionally included in the Accept-* headersare also supported:

  1. $acceptHeader = 'text/plain;q=0.5, text/html, text/*;q=0.8, */*;q=0.3';
  2. $accept = AcceptHeader::fromString($acceptHeader);
  3.  
  4. $quality = $accept->get('text/xml')->getQuality(); // $quality = 0.8
  5. $quality = $accept->get('application/xml')->getQuality(); // $quality = 0.3

Accessing other Data

The Request class has many other methods that you can use to access therequest information. Have a look atthe Request APIfor more information about them.

Overriding the Request

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

  1. use App\Http\SpecialRequest;
  2. use Symfony\Component\HttpFoundation\Request;
  3.  
  4. Request::setFactory(function (
  5. array $query = [],
  6. array $request = [],
  7. array $attributes = [],
  8. array $cookies = [],
  9. array $files = [],
  10. array $server = [],
  11. $content = null
  12. ) {
  13. return new SpecialRequest(
  14. $query,
  15. $request,
  16. $attributes,
  17. $cookies,
  18. $files,
  19. $server,
  20. $content
  21. );
  22. });
  23.  
  24. $request = Request::createFromGlobals();

Response

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

  1. use Symfony\Component\HttpFoundation\Response;
  2.  
  3. $response = new Response(
  4. 'Content',
  5. Response::HTTP_OK,
  6. ['content-type' => 'text/html']
  7. );

This information can also be manipulated after the Response object creation:

  1. $response->setContent('Hello World');
  2.  
  3. // the headers public attribute is a ResponseHeaderBag
  4. $response->headers->set('Content-Type', 'text/plain');
  5.  
  6. $response->setStatusCode(Response::HTTP_NOT_FOUND);

When setting the Content-Type of the Response, you can set the charset,but it is better to set it via thesetCharset() method:

  1. $response->setCharset('ISO-8859-1');

Note that by default, Symfony assumes that your Responses are encoded inUTF-8.

Sending the Response

Before sending the Response, you can optionally call theprepare() method to fix anyincompatibility with the HTTP specification (e.g. a wrong Content-Type header):

  1. $response->prepare($request);

Sending the response to the client is done by calling the methodsend():

  1. $response->send();

Setting Cookies

The response cookies can be manipulated through the headers publicattribute:

  1. use Symfony\Component\HttpFoundation\Cookie;
  2.  
  3. $response->headers->setCookie(Cookie::create('foo', 'bar'));

ThesetCookie()method takes an instance ofCookie as an argument.

You can clear a cookie via theclearCookie() method.

Note you can create aCookie object from a raw headervalue using fromString().

Managing the HTTP Cache

The Response class has a rich setof methods to manipulate the HTTP headers related to the cache:

Note

The methods setExpires(),setLastModified() andsetDate() accept anyobject that implements \DateTimeInterface, including immutable date objects.

The setCache() methodcan be used to set the most commonly used cache information in one methodcall:

  1. $response->setCache([
  2. 'etag' => 'abcdef',
  3. 'last_modified' => new \DateTime(),
  4. 'max_age' => 600,
  5. 's_maxage' => 600,
  6. 'private' => false,
  7. 'public' => true,
  8. ]);

To check if the Response validators (ETag, Last-Modified) match aconditional value specified in the client Request, use theisNotModified()method:

  1. if ($response->isNotModified($request)) {
  2. $response->send();
  3. }

If the Response is not modified, it sets the status code to 304 and removes theactual response content.

Redirecting the User

To redirect the client to another URL, you can use theRedirectResponse class:

  1. use Symfony\Component\HttpFoundation\RedirectResponse;
  2.  
  3. $response = new RedirectResponse('http://example.com/');

Streaming a Response

The StreamedResponse class allowsyou to stream the Response back to the client. The response content isrepresented by a PHP callable instead of a string:

  1. use Symfony\Component\HttpFoundation\StreamedResponse;
  2.  
  3. $response = new StreamedResponse();
  4. $response->setCallback(function () {
  5. var_dump('Hello World');
  6. flush();
  7. sleep(2);
  8. var_dump('Hello World');
  9. flush();
  10. });
  11. $response->send();

Note

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

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

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

Serving Files

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

  1. use Symfony\Component\HttpFoundation\HeaderUtils;
  2. use Symfony\Component\HttpFoundation\Response;
  3. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  4.  
  5. $fileContent = ...; // the generated file content
  6. $response = new Response($fileContent);
  7.  
  8. $disposition = HeaderUtils::makeDisposition(
  9. HeaderUtils::DISPOSITION_ATTACHMENT,
  10. 'foo.pdf'
  11. );
  12.  
  13. $response->headers->set('Content-Disposition', $disposition);

Alternatively, if you are serving a static file, you can use aBinaryFileResponse:

  1. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  2.  
  3. $file = 'path/to/file.txt';
  4. $response = new BinaryFileResponse($file);

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

  1. 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. <IfModule mod_xsendfile.c>
  2. # This is already present somewhere...
  3. XSendFile on
  4. XSendFilePath ...some path...
  5.  
  6. # This needs to be added:
  7. <IfModule mod_headers.c>
  8. RequestHeader set X-Sendfile-Type X-Sendfile
  9. </IfModule>
  10. </IfModule>

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

  1. // ...
  2. $response->headers->set('Content-Type', 'text/plain');
  3. $response->setContentDisposition(
  4. ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  5. 'filename.txt'
  6. );

It is possible to delete the file after the request is sent with thedeleteFileAfterSend() 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 Streaminstance to BinaryFileResponse. This will disable Range and Content-Lengthhandling, switching to chunked encoding instead:

  1. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  2. use Symfony\Component\HttpFoundation\File\Stream;
  3.  
  4. $stream = new Stream('path/to/stream');
  5. $response = new BinaryFileResponse($stream);

Note

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

Creating a JSON Response

Any type of response can be created via theResponse class by setting theright content and headers. A JSON response might look like this:

  1. use Symfony\Component\HttpFoundation\Response;
  2.  
  3. $response = new Response();
  4. $response->setContent(json_encode([
  5. 'data' => 123,
  6. ]));
  7. $response->headers->set('Content-Type', 'application/json');

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

  1. use Symfony\Component\HttpFoundation\JsonResponse;
  2.  
  3. // if you know the data to send when creating the response
  4. $response = new JsonResponse(['data' => 123]);
  5.  
  6. // if you don't know the data to send when creating the response
  7. $response = new JsonResponse();
  8. // ...
  9. $response->setData(['data' => 123]);
  10.  
  11. // if the data to send is already encoded in JSON
  12. $response = JsonResponse::fromJsonString('{ "data": 123 }');

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

Caution

To avoid XSSI JSON Hijacking, you should pass an associative arrayas the outer-most array to JsonResponse and not an indexed array sothat the final result is an object (e.g. {"object": "not inside an array"})instead of an array (e.g. [{"object": "inside an array"}]). Readthe 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.

JSONP Callback

If you're using JSONP, you can set the callback function that the data shouldbe passed to:

  1. $response->setCallback('handleResponse');

In this case, the Content-Type header will be text/javascript andthe response content will look like this:

  1. handleResponse({'data': 123});

Session

The session information is in its own document: Session Management.

Learn More