Matt
Matt

Reputation: 15

How to start a php session() and access $_SESSION in CakePHP 3.x?

I see from the CakePHP 3.2 documentation that to configure a session I need to use write(), so I tried that in my controller like this:

use App\Controller\AppController;
use Cake\Core\Configure;

class RatingsController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
        $this->loadComponent('Paginator');
        Configure::write('Session', ['defaults' => 'php']);
   }
}

But this doesn't seem to set up a $_SESSION array if executed in my controller.

I thought I had a workaround by setting up Auth, and thereby was able to access $_SESSION, but then when I open the controller by adding $this->Auth->allow(); to the init above, the session variable no longer exists.

Where do I need to configure Cake to start a session?

Upvotes: 0

Views: 2068

Answers (1)

code-kobold
code-kobold

Reputation: 824

CakePHP binds sessions to the Request, e.g. set a value to a key in your Controller:

$this->request->session()->write('defaults', 'php')

Then, e.g. in your Template read the Session by key:

$this->request->session()->read('defaults')

Upvotes: 3

Related Questions