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

Phalcon session not working properly

Ok so i have my session declared like so:

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

The reason why i have session write close is to prevent session blocking. Then i tried inside setting a session variable inside a controller

$this->session->start();
$this->session->set('auth', 1);
session_write_close();
echo $this->session->get('auth'); // 1

it properly sets the auth variables but when i try to login, the auth variable inside the security plugin is NULL

if(!$this->session->has('auth')){
    $dispatcher->forward(array(
        'controller'=>'errors',
        'action'=>'show404',
        'params'=>$this->session->get('auth');
    ));
}

in my view, `show404.volt'

<?php var_dump($this->dispatcher->getParams()); //NULL ?>

and what's really weird is that, the session in the plugin is not started, and even when i start the session it is still the same, the auth variable is null.

Unless you have multiple iframes loading concurrently, you don't need session_write_close(). Even if you do have multiple iframes, the delay in loading will likely be so tiny as to be unnoticable. Network latency would be a bigger issue. In my 12 years working with PHP, I've never once needed to use it.

So get rid of all your session_write_close() calls, because like the method name says, it's closing the session. That's your problem.

Also, every time you set a session variable, you don't need to re-call session_start(). start() will get called the first time the service is retrieved from the DI, and the session will remain open for the remainder of the request.

edited Apr '16

I think Dylan Anderson's answer is correct. Why are you calling session_write_close() ?

In any case, best approach to debug session issues is to use Network tab in Developer tools in Firefox (or Chrome). First open Private tab, and watch in Network tab (F12 shortcut) what is the first GET request to your page. What cookie value do you get on first page load in HTTP header "Set-Cookie". That value should remain the same as long as you're on that site and you are not jumping off one main domain to subdomains etc.



3.7k

The session_write_close() is used to prevent blocking of users, if i have a long running script with the session automatically started, then users requesting for my site will be blocked until the long running script ends. That's why i manually call session_write_close() to allow users use the session then explicitly call the $this->session->start() to start using the session again.



125.8k
Accepted
answer

Sessions are unique to each user, and are stored in separate files. One user's long-running script cannot affect other users' session access.