0

I am doing a cakephp project. I was stuck here. I want to get the previous url in cakephp 3.2,but its not working. Here the link is present in email ,after clicking upon that link i will redirect to login page and after login ,i wnato to redirect to that previous url means the url present in mail only. I have written the below code to do it.

 $rU = $this->request->referer();
        if (!stristr($rU, "users/login") && !stristr($rU, "login") && !stristr($rU, "users/register") && !stristr($rU, "register") && !stristr($rU, "appadmins") && !stristr($rU, "js") && !stristr($rU, "css") && !stristr($rU, "ajax")) {
            $this->request->session()->write('visited_page',$rU);
        }

Plesae suggst me. Any suggestion will highly appreciate. Thank you.

sradha
  • 2,216
  • 1
  • 28
  • 48

2 Answers2

3

Cakephp provides the feature to redirect users back to where they came from.

Its AuthComponent::redirectUrl()

After the login redirect them to redirectUrl like below
$this->redirect($this->Auth->redirectUrl())

For more info visit here

Pradeep Singh
  • 1,282
  • 2
  • 19
  • 35
1

First in AppController.php. Inside beforeFilter function store previous url in session

public function beforeFilter(){
  $url = Router::url(NULL, true); //complete url
  if (!preg_match('/login|logout/i', $url)){ // Restrict login and logout actions
    $this->Session->write('prevUrl', $url);
  }
}

Use where you need to redirect

if ($this->Session->read('prevUrl')){
$this->redirect($this->Session->read('prevUrl'));
exit;
}

This is working in cakephp 2.6 change beforeFilter function in cakephp 3 as

public function beforeFilter(\Cake\Event\Event $event){
  $url = Router::url(NULL, true); //complete url
if (!preg_match('/login|logout/i', $url)){ // Restrict login and logout actions
    $session = $this->request->session();
    $session->write('prevUrl', $url);
 }
}

Use where you need to redirect

$session = $this->request->session();
if($session->read('prevUrl')){
   $this->redirect($session->read('prevUrl'));
   exit;
}
Sudhir
  • 835
  • 11
  • 31