Reputation: 799
I would like to enable session in Symfony2, but I don't know how can I do that.
I set my config file like this:
#app/config/config.yml
framework:
session:
name: session
cookie_lifetime: 0
cookie_httponly: true
But it seems to my session is still disabled and not started. I tested this code in my controller:
echo ( session_status() !== PHP_SESSION_ACTIVE )
? "Session is not started!"
: "Session OK";
And it return "Session is not started!". It works only when I set:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
But this is very ugly solution, especially that I am working in Symfony2. Do you have any ideas?
Upvotes: 0
Views: 1235
Reputation: 4766
You don't need to acitivate it, it's set per default with symfony.
The default entry is this:
framework:
session: ~
You also don't need to start a new session (in fact you'll receive an error because it's already started from symfony).
15.04.2016 Edit:
The Syntax is a bit different by now
Controller
$session = $this->get('session');
Twig
app.session
Old Version:
You just need to get the session in your controller from the Request!
$session = $this->getRequest()->getSession();
That's all.
In Twig you can access it via
app.request.session
Upvotes: 3
Reputation: 4564
Syntax of Session in Symfony2 is bit 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');
Upvotes: 0
Reputation: 4275
In app/config/config.yml, under framework section, you must have a session item :
framework:
# ...
session: ~
Just have a look at : http://symfony.com/doc/current/reference/configuration/framework.html#session
Upvotes: 0
Reputation: 4210
In my current project I've enabled session like this and it works fine:
(under framework option)
session:
handler_id: ~
cookie_domain: .st.dev
name: SFSESSID
cookie_lifetime: 0
save_path: "%kernel.cache_dir%/sessions"
gc_divisor: 2000
gc_maxlifetime: 86400
you can also look at this documenation page
Upvotes: 0
Reputation: 685
Sessions are automatically started when you read/write data in it if you use a recent version of Symfony2.
However, you can force it to start by instanciating a session variable and start it:
$session = new Session();
$session->start();
You should take a look at the doc. Be careful, Symfony sessions are not the same thing as native sessions.
http://symfony.com/doc/current/components/http_foundation/sessions.html
http://symfony.com/doc/current/components/http_foundation/session_php_bridge.html
Upvotes: -1