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

Notice: A session had already been started - ignoring session_start() - Error

Hi,

I'm just getting started with Phalcon and currently am getting the error:

Notice: A session had already been started - ignoring session_start()

In my services.php file I have the following code blocks:

$di->set('session', function () {
    $session = new SessionAdapter(array('uniqueId' => 'TEST'));
    $session->start();
    return $session;
});

$di->set('security', function() {
    $security = new Security();
    return $security;
}, true);

And I am using the Security script from Milad on this page:

https://forum.phalcon.io/discussion/2507/opening-several-pages-with-forms-invalidate-security-tokens

 <?php

    class Security extends \Phalcon\Security
    {
        public function getTokenKey($numberBytes = 13)
        {
            $key = '$PHALCON/CSRF/KEY$';

            $tokenKey = \Phalcon\DI::getDefault()->get('session')->$key;

            if ($tokenKey)
            {
                return $tokenKey;
            }

            return parent::getTokenKey($numberBytes);
        }

        public function getToken($numberBytes = 32)
        {
            $key = '$PHALCON/CSRF$';

            $token = \Phalcon\DI::getDefault()->get('session')->$key;

            if ($token)
            {
                return $token;
            }

            return parent::getToken($numberBytes);
        }
    }

Please can anyone advice why I am getting this error.

Thanks



6.4k
Accepted
answer

Set session as shared service

<?php

$di->set('session', function () {
    $session = new SessionAdapter(array('uniqueId' => 'TEST'));
    $session->start();
    return $session;
}, TRUE); // <-- HERE

// OR

$di->setShared('session', function () {
    $session = new SessionAdapter(array('uniqueId' => 'TEST'));
    $session->start();
    return $session;
});

// OR
$session = new SessionAdapter(array('uniqueId' => 'TEST'));
$session->start();

$di->set('session', $session);


3.1k

Thanksfor the help, answer accepted.