Like in classic PHP we use the magic variables to start and create sessions, so how to do that in Symfony?
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.
However, if you have the following configuration, Symfony will store the session data in files in the cache directory %kernel. cache_dir%/sessions . This means that when you clear the cache, any current sessions will also be deleted: YAML.
gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session. gc_probability and session. gc_divisor). Defaults to 1440 (24 minutes).
In Symfony2, the syntax is different:
$session = $this->getRequest()->getSession(); // store an attribute for reuse during a later user request $session->set('foo', 'bar'); // in another controller for another request $foo = $session->get('foo');
You can also get session variables from Twig, without having to pass the session variable explicitly (it's in the global 'app'):
{{ app.session.get('foo', 'bar'); }}
In your controller, you can access session variables through the user object.
// Get a session value $name = $this->getUser()->getAttribute('name', 'default_value'); // Set a session value $this->getUser()->setAttribute('name', $value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With