Symfony HttpFoundation component provides cookie and session management in an object-oriented manner. Cookie provides client-side data storage and it only supports a small amount of data. Usually, it is 2KB per domain and it depends on the browser. Session provides server-side data storage and it supports a large amount of data. Let us see how to create a cookie and session in a Symfony web application.
Symfony provides Cookie class to create a cookie item. Let us create a cookie color, which expires in 24 hours with value blue. The constructor parameter of the cookie class is as follows.
use Symfony\Component\HttpFoundation\Cookie; $cookie = new Cookie('color', 'green', strtotime('tomorrow'), '/', 'somedomain.com', true, true);
Symfony also provides the following string-based cookie creation option.
$cookie = Cookie::fromString('color = green; expires = Web, 4-May-2017 18:00:00 +0100; path=/; domain = somedomain.com; secure; httponly');
Now, the created cookie needs to be attached to the http response object's header as follows.
To get the cookie, we can use Request object as follows.
$cookie = $request->cookie->get('color');
Here, request->cookie is of type PropertyBag and we can manipulate it using PropertyBag methods.
Symfony provides a Session class implementing SessionInterface interface. The important session API are as follows,
start − Starts the session.
Session $session = new Session(); $session->start();
invalidate − Clears all session data and regenerates the session ID.
set − Stores data in the session using a key.
We can use any data in the session value, be in simple integer to complex objects.
get − Gets data from the session using the key.
$val = $session->get('key');
remove − Removes a key from the session.
clear − Removes a session data.
Session provides another useful feature called FlashBag. It is a special container inside the session holding the data only during page redirection. It is useful in http redirects. Before redirecting to a page, data can be saved in FlashBag instead of a normal session container and the saved data will be available in the next request (the redirected page). Then, the data will be invalidated automatically.
$session->getFlashBag()->add('key', 'value'); $session->getFlashBag()->get('key');