.. index:: single: HTTP single: HttpFoundation
The HttpFoundation Component defines an object-oriented layer for the HTTP specification.
In PHP, the request is represented by some global variables ($_GET
,
$_POST
, $_FILE
, $_COOKIE
, $_SESSION
...) and the response is
generated by some functions (echo
, header
, setcookie
, ...).
The Symfony2 HttpFoundation component replaces these default PHP global variables and functions by an Object-Oriented layer.
You can install the component in many different ways:
- Use the official Git repository (https://github.com/symfony/HttpFoundation);
- Install it via PEAR ( pear.symfony.com/HttpFoundation);
- Install it via Composer (symfony/http-foundation on Packagist).
The most common way to create request is to base it on the current PHP global variables with :method:`Symfony\\Component\\HttpFoundation\\Request::createFromGlobals`:
use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals();
which is almost equivalent to the more verbose, but also more flexible, :method:`Symfony\\Component\\HttpFoundation\\Request::__construct` call:
$request = new Request($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
A Request object holds information about the client request. This information can 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 :ref:`below<component-foundation-attributes>`)files
: equivalent of$_FILE
;server
: equivalent of$_SERVER
;headers
: mostly equivalent to a sub-set of$_SERVER
($request->headers->get('Content-Type')
).
Each property is a :class:`Symfony\\Component\\HttpFoundation\\ParameterBag` instance (or a sub-class of), which is a data holder class:
request
: :class:`Symfony\\Component\\HttpFoundation\\ParameterBag`;query
: :class:`Symfony\\Component\\HttpFoundation\\ParameterBag`;cookies
: :class:`Symfony\\Component\\HttpFoundation\\ParameterBag`;attributes
: :class:`Symfony\\Component\\HttpFoundation\\ParameterBag`;files
: :class:`Symfony\\Component\\HttpFoundation\\FileBag`;server
: :class:`Symfony\\Component\\HttpFoundation\\ServerBag`;headers
: :class:`Symfony\\Component\\HttpFoundation\\HeaderBag`.
All :class:`Symfony\\Component\\HttpFoundation\\ParameterBag` instances have methods to retrieve and update its data:
- :method:`Symfony\\Component\\HttpFoundation\\ParameterBag::all`: Returns the parameters;
- :method:`Symfony\\Component\\HttpFoundation\\ParameterBag::keys`: Returns the parameter keys;
- :method:`Symfony\\Component\\HttpFoundation\\ParameterBag::replace`: Replaces the current parameters by a new set;
- :method:`Symfony\\Component\\HttpFoundation\\ParameterBag::add`: Adds parameters;
- :method:`Symfony\\Component\\HttpFoundation\\ParameterBag::get`: Returns a parameter by name;
- :method:`Symfony\\Component\\HttpFoundation\\ParameterBag::set`: Sets a parameter by name;
- :method:`Symfony\\Component\\HttpFoundation\\ParameterBag::has`: Returns true if the parameter is defined;
- :method:`Symfony\\Component\\HttpFoundation\\ParameterBag::remove`: Removes a parameter.
The :class:`Symfony\\Component\\HttpFoundation\\ParameterBag` instance also has some methods to filter the input values:
- :method:`Symfony\\Component\\HttpFoundation\\Request::getAlpha`: Returns the alphabetic characters of the parameter value;
- :method:`Symfony\\Component\\HttpFoundation\\Request::getAlnum`: Returns the alphabetic characters and digits of the parameter value;
- :method:`Symfony\\Component\\HttpFoundation\\Request::getDigits`: Returns the digits of the parameter value;
- :method:`Symfony\\Component\\HttpFoundation\\Request::getInt`: Returns the parameter value converted to integer;
- :method:`Symfony\\Component\\HttpFoundation\\Request::filter`: Filters the
parameter by using the PHP
filter_var()
function.
All getters takes up to three arguments: the first one is the parameter name and the second one is the default value to return if the parameter does not exist:
// the query string is '?foo=bar' $request->query->get('foo'); // returns bar $request->query->get('bar'); // returns null $request->query->get('bar', 'bar'); // returns 'bar'
When PHP imports the request query, it handles request parameters like
foo[bar]=bar
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. But
sometimes, you might want to get the value for the "original" parameter name:
foo[bar]
. This is possible with all the ParameterBag getters like
:method:`Symfony\\Component\\HttpFoundation\\Request::get` via the third
argument:
// the query string is '?foo[bar]=bar' $request->query->get('foo'); // returns array('bar' => 'bar') $request->query->get('foo[bar]'); // returns null $request->query->get('foo[bar]', null, true); // returns 'bar'
Last, but not the least, you can also store additional data in the request,
thanks to the attributes
public property, which is also an instance of
:class:`Symfony\\Component\\HttpFoundation\\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. For information
on how this is used in the Symfony2 framework, see :ref:`read more<book-fundamentals-attributes>`.
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 the :method:`Symfony\\Component\\HttpFoundation\\Request::getPathInfo` method:
// for a request to http://example.com/blog/index.php/post/hello-world // the path info is "/post/hello-world" $request->getPathInfo();
Instead of creating a Request based on the PHP globals, you can also simulate a Request:
$request = Request::create('/hello-world', 'GET', array('name' => 'Fabien'));
The :method:`Symfony\\Component\\HttpFoundation\\Request::create` method creates a request based on a path info, a method and some parameters (the query parameters or the request ones depending on the HTTP method); and of course, you an 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 :method:`Symfony\\Component\\HttpFoundation\\Request::overrideGlobals`:
$request->overrideGlobals();
Tip
You can also duplicate an existing query via :method:`Symfony\\Component\\HttpFoundation\\Request::duplicate` or change a bunch of parameters with a single call to :method:`Symfony\\Component\\HttpFoundation\\Request::initialize`.
If you have a session attached to the Request, you can access it via the :method:`Symfony\\Component\\HttpFoundation\\Request::getSession` method; the :method:`Symfony\\Component\\HttpFoundation\\Request::hasPreviousSession` method tells you if the request contains a Session which was started in one of the previous requests.
The Request class has many other methods that you can use to access the request information. Have a look at the API for more information about them.
A :class:`Symfony\\Component\\HttpFoundation\\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:
use Symfony\Component\HttpFoundation\Response; $response = new Response('Content', 200, array('content-type' => 'text/html'));
These information can also be manipulated after the Response object creation:
$response->setContent('Hello World'); // the headers public attribute is a ResponseHeaderBag $response->headers->set('Content-Type', 'text/plain'); $response->setStatusCode(404);
When setting the Content-Type
of the Response, you can set the charset,
but it is better to set it via the
:method:`Symfony\\Component\\HttpFoundation\\Response::setCharset` method:
$response->setCharset('ISO-8859-1');
Note that by default, Symfony assumes that your Responses are encoded in UTF-8.
Before sending the Response, you can ensure that it is compliant with the HTTP specification by calling the :method:`Symfony\\Component\\HttpFoundation\\Response::prepare` method:
$response->prepare($request);
Sending the response to the client is then as simple as calling :method:`Symfony\\Component\\HttpFoundation\\Response::send`:
$response->send();
The response cookies can be manipulated though the headers
public
attribute:
use Symfony\Component\HttpFoundation\Cookie; $response->headers->setCookie(new Cookie('foo', 'bar'));
The :method:`Symfony\\Component\\HttpFoundation\\ResponseHeaderBag::setCookie` method takes an instance of :class:`Symfony\\Component\\HttpFoundation\\Cookie` as an argument.
You can clear a cookie via the :method:`Symfony\\Component\\HttpFoundation\\Response::clearCookie` method.
The :class:`Symfony\\Component\\HttpFoundation\\Response` class has a rich set of methods to manipulate the HTTP headers related to the cache:
- :method:`Symfony\\Component\\HttpFoundation\\Response::setPublic`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::setPrivate`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::expire`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::setExpires`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::setMaxAge`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::setSharedMaxAge`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::setTtl`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::setClientTtl`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::setLastModified`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::setEtag`;
- :method:`Symfony\\Component\\HttpFoundation\\Response::setVary`;
The :method:`Symfony\\Component\\HttpFoundation\\Response::setCache` method can be used to set the most commonly used cache information in one method call:
$response->setCache(array( 'etag' => 'abcdef', 'last_modified' => new \DateTime(), 'max_age' => 600, 's_maxage' => 600, 'private' => false, 'public' => true, ));
To check if the Response validators (ETag
, Last-Modified
) match a
conditional value specified in the client Request, use the
:method:`Symfony\\Component\\HttpFoundation\\Response::isNotModified`
method:
if ($response->isNotModified($request)) { $response->send(); }
If the Response is not modified, it sets the status code to 304 and remove the actual response content.
To redirect the client to another URL, you can use the :class:`Symfony\\Component\\HttpFoundation\\RedirectResponse` class:
use Symfony\Component\HttpFoundation\RedirectResponse; $response = new RedirectResponse('http://example.com/');
.. versionadded:: 2.1 Support for streamed responses was added in Symfony 2.1.
The :class:`Symfony\\Component\\HttpFoundation\\StreamedResponse` class allows you to stream the Response back to the client. The response content is represented by a PHP callable instead of a string:
use Symfony\Component\HttpFoundation\StreamedResponse; $response = new StreamedResponse(); $response->setCallback(function () { echo 'Hello World'; flush(); sleep(2); echo 'Hello World'; flush(); }); $response->send();
.. versionadded:: 2.1 The ``makeDisposition`` method was added in Symfony 2.1.
When uploading a file, you must add a Content-Disposition
header to your
response. While creating this header for basic file downloads is easy, using
non-ASCII filenames is more involving. The
:method:`Symfony\\Component\\HttpFoundation\\Response::makeDisposition`
abstracts the hard work behind a simple API:
use Symfony\Component\HttpFoundation\ResponseHeaderBag; $d = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'foo.pdf'); $response->headers->set('Content-Disposition', $d);
The session information is in its own document: :doc:`/components/http_foundation/sessions`.