dtudj42064 2014-08-14 12:32
浏览 57
已采纳

如何在Symfony2中启用会话?

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?

  • 写回答

5条回答 默认 最新

  • dsfdfd1211 2014-08-14 12:39
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?