I would like to know how I can use a function in cakePHP that will always be call when I load a page?
More precisions with this example:
I have my main page: index.ctp
I have another page: profil.ctp
What I want is, when I try to access profil.ctp, if I’m not logged, it will automatically redirect me to the index.ctp page.
What I already done:
UsersController:
function index() {
if (!empty($this->data))
$this->Session->write(array('User' => array('connected' => true)));
}
ProfilsController:
function index() {
if (!$this->Session->read('connected'))
$this->redirect(array('controller' => 'users', 'action' => 'index'));
}
The problem is that I don’t want to add this code to each pages, and each functions of all my controllers.
Any ideas ?
Regards.
Put the code in your
AppController.phps beforeFilter()If you use the
beforeFilterin other controllers make sure to callparentbefore the other code.In each controller, the
beforeFilter()is called, which then triggers the AppController (parent)beforeFilter().