Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Sessions in Symfony? [closed]

Like in classic PHP we use the magic variables to start and create sessions, so how to do that in Symfony?

like image 529
Harish Kurup Avatar asked Nov 19 '09 07:11

Harish Kurup


People also ask

How session works 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.

Where does Symfony store sessions?

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.

What is session Gc_maxlifetime?

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).


2 Answers

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'); }} 
like image 66
Tac Tacelosky Avatar answered Sep 18 '22 17:09

Tac Tacelosky


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); 
like image 28
Franz Avatar answered Sep 20 '22 17:09

Franz