We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Session already started

Hi there,

I occasionally get an error saying the session is already started when Phalcon accesses the 'session' closure. I've modified it with the following and it seems to work OK. Is there anything wrong with what I've done? Thanks.


    $di->set('session', function () {
        $session = new Phalcon\Session\Adapter\Files();

        if (!isset($_SESSION)) {
            $session->start();
        }

        return $session;
    });


125.8k
Accepted
answer

It's a little iffy because there may be situations where $_SESSION can exist after the session is closed. The accepted answere here: https://stackoverflow.com/questions/6249707/check-if-php-session-has-already-started seems helpful.

If you're really interested, you should try and find where the session actually gets started. Does that error fire every time the session service gets accessed, or just the second time?

Try changing $di->set to $di->setShared, which will cause Phalcon to only run the associated function once.



38.8k

Hi Quasi - many thanks for your comments. It doesn't happen the first time, but on subsequent occasions. I tried $di->setShared but it made no difference so I've updated the code along the lines of the StackOverflow solution you linked me to.

I'm using a content management framework (CMF) with the application I'm building and I have a suspicion that there is some influence from that source.

Cheers.