关于symfony的session和cookie
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.
Cookie
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.
name (type: string) - cookie name
value (type: string) - cookie value
expire (type: integer / string / datetime) - expiry information
path (type: string) - the server path in which the cookie is available
domain (type: string) – the domain address in which the cookie is available
secure (type: boolean) - whether the cookie needs to be transmitted in HTTPS connection
httpOnly (type: boolean) - whether the cookie is available only in HTTP protocol
ex:
use Symfony\Component\HttpFoundation\Cookie;
$cookie = new Cookie('color', 'green', strtotime('tomorrow'), '/',
'somedomain.com', true, true);
Now, the created cookie needs to be attached to the http response object's header as follows.
$response->headers->setCookie($cookie);
To get the cookie, we can use Request object as follows
$cookie = $request->cookie->get('color');
Session
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.
$session->set('key', 'value');
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.
