The HttpFoundation Component
Edit this pageWarning: You are browsing the documentation for Symfony 2.0, which is no longer maintained.
Read the updated version of this page for Symfony 7.0 (the current stable version).
The HttpFoundation Component
The HttpFoundation Component defines an object-oriented layer for the HTTP specification.
In PHP, the request is represented by some global variables ($_GET
,
$_POST
, $_FILES
, $_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.
Installation
You can install the component in many different ways:
- Use the official Git repository (https://github.com/symfony/HttpFoundation);
- Install it via Composer (
symfony/http-foundation
on Packagist).
Request
The most common way to create request is to base it on the current PHP global variables with createFromGlobals():
1 2 3
use Symfony\Component\HttpFoundation\Request;
$request = Request::createFromGlobals();
which is almost equivalent to the more verbose, but also more flexible, __construct() call:
1 2 3 4 5 6 7 8
$request = new Request(
$_GET,
$_POST,
array(),
$_COOKIE,
$_FILES,
$_SERVER
);
Accessing Request Data
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 below)files
: equivalent of$_FILES
;server
: equivalent of$_SERVER
;headers
: mostly equivalent to a sub-set of$_SERVER
($request->headers->get('Content-Type')
).
Each property is a ParameterBag instance (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 have methods to retrieve and update its 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 also has 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;
- 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 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:
1 2 3 4 5 6 7 8 9 10
// 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
get() via the third
argument:
1 2 3 4 5 6 7 8 9 10
// 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'
Finally, you can also store additional data in the request,
thanks to the public attributes
property, 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. For information
on how this is used in the Symfony2 framework, see read more.
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 the getPathInfo() method:
1 2 3
// for a request to http://example.com/blog/index.php/post/hello-world
// the path info is "/post/hello-world"
$request->getPathInfo();
Simulating a Request
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',
array('name' => 'Fabien')
);
The 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 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():
1
$request->overrideGlobals();
Tip
You can also duplicate an existing query via duplicate() or change a bunch of parameters with a single call to initialize().
Accessing the Session
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.
Accessing `Accept-*` Headers Data
You can easily access basic data extracted from Accept-*
headers
by 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;
Accessing other Data
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.
Response
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:
1 2 3 4 5 6 7
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:
1 2 3 4 5 6
$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
setCharset() method:
1
$response->setCharset('ISO-8859-1');
Note that by default, Symfony assumes that your Responses are encoded in UTF-8.
Sending the Response
Before sending the Response, you can ensure that it is compliant with the HTTP specification by calling the prepare() method:
1
$response->prepare($request);
Sending the response to the client is then as simple as calling send():
1
$response->send();
Setting Cookies
The response cookies can be manipulated though the headers
public
attribute:
1 2 3
use Symfony\Component\HttpFoundation\Cookie;
$response->headers->setCookie(new Cookie('foo', 'bar'));
The setCookie() method takes an instance of Cookie as an argument.
You can clear a cookie via the clearCookie() method.
Managing the HTTP Cache
The Response class has a rich set of methods to manipulate the HTTP headers related to the cache:
- setPublic();
- setPrivate();
- expire();
- setExpires();
- setMaxAge();
- setSharedMaxAge();
- setTtl();
- setClientTtl();
- setLastModified();
- setEtag();
- setVary();
The setCache() method can be used to set the most commonly used cache information in one method call:
1 2 3 4 5 6 7 8
$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
isNotModified()
method:
1 2 3
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.
Redirecting the User
To redirect the client to another URL, you can use the RedirectResponse class:
1 2 3
use Symfony\Component\HttpFoundation\RedirectResponse;
$response = new RedirectResponse('http://example.com/');
Creating a JSON Response
Any type of response can be created via the Response class by setting the right content and headers. A JSON response might look like this:
1 2 3 4 5 6 7
use Symfony\Component\HttpFoundation\Response;
$response = new Response();
$response->setContent(json_encode(array(
'data' => 123,
)));
$response->headers->set('Content-Type', 'application/json');
Session
TBD -- This part has not been written yet as it will probably be refactored soon in Symfony 2.1.