6
votes

In my CakePHP 2 application i have a problem with beforeFilter. In this thread it worked well. Because of old version of CakePHP.

In my code, If user is not authorized, I want to show him "anotherview.ctp". I don't want to redirect visitor to another page. (because of adsense issues)

When i use "this->render" in beforeFilter, the code in my "index" action is also run. I want to stop the execution after the last line of "beforeFilter". When I add "exit()" to beforeFilter, it broke my code.

How can I stop execution in beforeFilter without breaking code?

class MyController extends AppController {
    function beforeFilter() {
        if ( $authorization == false )  {
                $this->render('anotherview');
                //exit();
            }
        }
    }

    function index() {
        // show authorized staff
    }           
}
4

4 Answers

20
votes

Try:

$this->response->send();
$this->_stop();
4
votes

I stumbled across this thread while trying to do the same thing. The accepted answer works but omits an important detail. I'm trying to render a layout (not a view) and I had to add an additional line to prevent the original request's view from throwing errors.

Inside AppController::beforeFilter():

$this->render(FALSE, 'maintenance'); //I needed to add this
$this->response->send();
$this->_stop();
1
votes

or alternatively - redirect to another view:

if ( $authorization == false )  {
    $this->redirect('/users/not_authorized');
}
0
votes

For CakePHP 3.5 this is what worked for me:

$event->setResult($this->render('anotherview'));

This will also enable you to use the debugger. CakePHP Debugger stopped working when I used the exit; statement.