Sessions
Symfony provides a session object and several utilities that you can use to store information about the user between requests.
Configuration
Sessions are provided by the HttpFoundation component, which is included in all Symfony applications, no matter how you installed it. Before using the sessions, check their default configuration:
Setting the handler_id config option to null means that Symfony will
use the native PHP session mechanism. The session metadata files will be stored
outside of the Symfony application, in a directory controlled by PHP. Although
this usually simplifies things, some session expiration related options may not
work as expected if other applications that write to the same directory have
short max lifetime settings.
If you prefer, you can use the session.handler.native_file service as
handler_id to let Symfony manage the sessions itself. Another useful option
is save_path, which defines the directory where Symfony will store the
session metadata files:
Check out the Symfony config reference to learn more about the other available Session configuration options. You can also store sessions in a database.
Basic Usage
The session is available through the Request object and the RequestStack
service. Symfony injects the request_stack service in services and controllers
if you type-hint an argument with Symfony\Component\HttpFoundation\RequestStack:
use Symfony\Component\HttpFoundation\RequestStack;
class SomeService
{
private $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function someMethod()
{
$session = $this->requestStack->getSession();
// stores an attribute in the session for later reuse
$session->set('attribute-name', 'attribute-value');
// gets an attribute by name
$foo = $session->get('foo');
// the second argument is the value returned when the attribute doesn't exist
$filters = $session->get('filters', []);
// ...
}
}
Stored attributes remain in the session for the remainder of that user’s session.
By default, session attributes are key-value pairs managed with the
Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag
class.
Avoid Starting Sessions for Anonymous Users
Sessions are automatically started whenever you read, write or even check for the existence of data in the session. This may hurt your application performance because all users will receive a session cookie. In order to prevent that, you must completely avoid accessing the session.