How to go back to referer page in CakePHP after login

vitto picture vitto · Jan 4, 2013 · Viewed 18.4k times · Source

I have a problem on going back to referer page:

first url: http://site.com/venue/apartments/1564/venue-name
referer url: null

In this page I can edit stuff inside, so I have a login button to go to the login page, after a successful login, I would like to turn back to the first url.

second url: http://site.com/users/login
referer url: http://site.com/venue/apartments/1564/venue-name

when I try to login, due to the CakePHP action rules, i have to refresh the login page to check the credentials, the problem starts here:

third url: http://site.com/users/login
referer url: http://site.com/users/login

by refreshing the page, and checking the credentials in the login action of users controller I get as refer the same page where I was before, and now I can't going back to the first url.

I tried some solution by setting a session variable in the AppController which checks if I'm not in the login action page and doing this:

AppController.php

public function beforeFilter () {
    $this->setRedirect();
}

public function setRedirect () {
    if ($this->request->params['controller'] != 'users' && $this->request->params['action'] != 'login') {
        $this->Session->write('redir', array('controller'=>$this->request->params['controller'], 'action'=>$this->request->params['action'], implode($this->request->params['pass'], '/')));
    }
}

By testing the session var with debug($this->Session->write('redir')); everything would seem to works perfect until I go to the login action:

UsersController.php

public function login () {
    if ($this->request->is ('post')){
        if ($this->Auth->login()) {
            $redir = $this->Session->read('redir');
            if (!empty($redir)) {
                $this->redirect ($redir);
            } else {
                $this->redirect ($this->Auth->redirect());
            }
        }
    }
}

Doing this break the application and if I debug($redir); var i get:

array(
    'controller' => 'js',
    'action' => 'jquery',
    (int) 0 => 'plugin/jquery.validata.1.7.min' // just a jquery plugin loaded in default.ctp
)

instead of

array(
    'controller' => 'venue',
    'action' => 'apartments',
    (int) 0 => '1564/venue-name'
)

If I debug($redir); in any other view of the entire site, everything works well and I get the right data.

I thought in some kind of Session protection routine for $this->Auth->login() action but it's totally nonsense for me.

How can I just redirect the user logged to the last page which isn't the login view page?

Answer

emersonthis picture emersonthis · May 2, 2013

Have you tried this: $this->redirect(Controller::referer());?

I'd have to reread your whole question to be sure, but this should also work: $this->redirect( $this->referer() );