Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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:

http://forum.phalconphp.com/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.3k
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);


1.9k

Thanksfor the help, answer accepted.