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.

Easy way to check session

How to check for session in each controller. I want to check session on controller level not in the functions inside the controller. If session is not set, it will redirect to login page.



25.2k
Accepted
answer
edited Mar '14

Hi, if you want to check session for every controllers you can do that in ControllerBase initialize() function (assuming that all of your controllers extends from ControllerBase). Otherwise, for each controller in wich you want a session check, put that in each controller initialize() function.



12.9k

Please post initialize() function.

ControllerBase.php

use Phalcon\Mvc\Controller; class IndexController extends Controller {

}

Other_Controllers.php

class IndexController extends ControllerBase {

}

I think the above snippet is correct.



25.2k
edited Mar '14
use Phalcon\Mvc\Controller;
class ControllerBase extends Controller
{
    protected function initialize()
    {
          if(!$session->has('auth')) {
                // assuming that auth param is initialized after login
                $this->flash->error('Please login into the application');
                // then redirect to your login page
    }
}

For automatic process like ACL check I prefer to use beforeExecuteRoute instead of initialize

public function beforeExecuteRoute(Dispatcher $dispatcher)
{
    // ACL check or ...
}


12.9k

To add beforeExecuteRoute inside ControllerBase ? Please clarify

edited Mar '14

@a6oozar +1

Here is my implementation in simple app without ACL:

abstract class SecureController extends Controller
{
    public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher)
    {
        if (false === $this->auth->isLogged()) {
            if ($this->auth->hasRememberMe()) {
                $this->auth->loginWithRememberMe();
            } else {
                throw new AccessDeniedException();
            }
        }
    }
}

you can change throw exception to redirect to login page



12.9k

I am new to advanced PHP and Palcon. So I can't fully understand the code. Anyway thanks everyone for fast help. The community as fast as Phalcon.



12.9k

I try le51s code I am getting the following error..

PHP Notice: Undefined variable: session in ......\IndexController.php on line 8

edited Mar '14

You should add Session Adapter to your applicaion DI for example for File adapter: otherwise it can`t be accessible in your MVC controllers by default.

        // Session
        $di->setShared('session', function() {
            $session = new Phalcon\Session\Adapter\Files();
            $session->start();
            return $session;
        });