开发者

CakePHP send current url as query string when user is redirected to login

In CakePHP when a user tries to access an action that is protected with the Au开发者_如何转开发th component they are redirected to the login page.

So for example if I tried to acccess: domain.com/posts/add it would take me to domain.com/users/login

What I want to do is when anything like this happens is add a query string with the previous url like so: domain.com/users/login?back=/posts/add This is because I have disabled autoRedirect so that the redirect is no longer based on the session.

How would I add this query string though? Thanks

Just to confirm I know how to redirect the user using the query string in the login method just not how to send the query string in the first place when a user is sent to the login page from action that requires authorisation.


I do it by accessing $this->Auth->redirect() in the login action, and parsing that value as a hidden param to the login form, check for it's existence if the form is submitted, and send the user back to it.

ie controller:

function login() {
    if($this->Auth->user()) { // User got logged in
         if(!empty($this->data['User']['referer']) {
             $this->redirect($this->data['User']['referer']);
         } else {
              // Take them to dashboard or something instead
         }
    } else {
         // Set return_to to last page
     $referer = $this->Auth->redirect();
         if($referer == $this->here) {
         $referer = false;
         }
         $this->set(compact('referer') );
    }
}

And in your form something like $this->Form->input('referer', array('type' => 'hidden', 'value' => $referer ?: false); - Note PHP 5.3 ternary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜