Mahdi Sabori
Mahdi Sabori

Reputation: 77

Symfony2: new Session() give error "A session had already been started..."

I'm amateure in symfony. I want use Session_id in my code

when i change php.ini and set session.auto.start variable true i give a symfony error after false this parameter i should use

$session = new Session();

but now i have a new error, when I execute indexAction() :

An exception has been thrown during the rendering of a template ("Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\artgirl\app\cache\dev\classes.php line 105") in "DotArtBundle:Basket:index.html.twig".
500 Internal Server Error - Twig_Error_Runtime
1 linked Exception: ErrorException »

BasketController :

class BasketController extends Controller {
    public function getStaticAction(){
        $session = new Session();
        $session->start();

        $em = $this->getDoctrine()->getManager();
        $sql  = "Select ... where basket_id = '".$session->getId()."'";
    }
    //###############################################
    public function indexAction(){
      $user = new User();
      $form = $this->createFormBuilder($user)
                   ->add('username', 'text')
                   ->add('password', 'text')
                   ->add('email', 'text')
                   ->getForm();
    return $this->render('DotArtBundle:Artist:register.html.twig', array('form' => $form->createView(l)));
    }
}

I use getStaticAction() in my base.html.twig

        {% set vPrice = render(controller('DotArtBundle:Basket:getStatic')) %}

Upvotes: 0

Views: 3945

Answers (1)

Glitch Desire
Glitch Desire

Reputation: 15061

In version 2.1 they changed how sessions work, instead of auto starting they're started on demand.

As I understand it, Symfony 2 sessions are incompatible with PHP sessions and Symfony replaces a lot of the base PHP session functions, therefore you need to turn off auto starting in php.ini and initialize a session with something like:

use Symfony/Component/HttpFoundation/Session/Session;
$session = new Session();
$session->start();

Then you should be able to do something like this wherever you need the ID:

$session = $this->getRequest()->getSession()->get('id');

Symfony explains their sessions handling over here, might be worth a read.

Upvotes: 2

Related Questions