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

Redirection loop because of the controller and action values

I'm just starting with Phalcon and decided to slowly port all of my current apps on it. And first problem I've encountered is the redirection to login form. In INVO, the Security.php beforeDispatch() contains call on Dispatcher::forward(), which will display the login form simply anywhere the user actually is. Well, I don't really want this behaviour and want to redirect user to the page with login form instead.

So, I've replaced the Dispatcher::forward() with Response::redirect() but got kicked in the head by infinite loop. The issue is that even after redirection, $dispatcher->getControllerName() still returns the previous controller and thus the ACL rule will fail again and so on.

Can I somehow tell dispatcher "you're done with this controller, forget about it" or am I actually doing it the wrong way? I simply want guest users to be redirected to the login form no matter what address they try to access.

My code is pretty much the same as the INVO, except for the replacement of the Dispatcher::forward() with Response::redirect().



40.8k
Accepted
answer
edited Mar '14

controllers/BaseController.php BaseController extends \Phalcon\Mvc\Controller

controllers/LoginController.php LoginController extends \Phalcon\Mvc\Controller

controllers/IndexController.php IndexController extends BaseController

controllers/WhateverController.php WhateverController extends BaseController

class BaseController extends \Phalcon\Mvc\Controller
{
    public function onConstruct()
    {
        if($allow==false) //your rules when you are sure if $allow is set in session or any other rules
        {
            $this->response->redirect("login/index");
        }
    }
}

This way you will get what you want :)



1.4k

Thanks. Will try it this way :)



293

I found must use send method append redirect like this:

$this->response->redirect('/user/login')->send();