简体   繁体   中英

Cakephp 3 redirect not working if exception is after

I have an action in a controller where i call to a function that checks if a cookie is set, if the cookie is not set then it should redirect to somewhere else.

In the same controller i have an evaluation for some variables, if they're not set then throw a forbidden exception but even when the cookie is not set it's not redirecting and the forbidden message appears

The correct action should be redirect and never evaluate for the variables when the cookie doesn't exist or at least that's what i need.

This function is in appController

public function isCookieSet(){
  if(!$this->Cookie->check('cookie')){
    return $this->redirect($this->referer());
  }
}

And the code inside my controller

public function editarImg($negocio_id=null){    

    $this->isCookieSet(); //should redirect here

    //but executes until here
    if((!isset($this->perRol['crear_negocios']) || $this->perRol['crear_negocios']==0) || 
      (!isset($this->perRol['cargar_elim_imagenes']) || $this->perRol['cargar_elim_imagenes']==0)){
      throw new ForbiddenException($this->getMensajeError(403));
    }

    ...
}

The code in the question can be rewritten (for clarity) like so:

public function editarImg($negocio_id=null){    
    if(!$this->Cookie->check('cookie')){
        $this->redirect($this->referer());
    }

    // more code

The return value of the call to redirect is being ignored, "more code" is always executed.

This is not how the method redirect is expected to be called, as mentioned in the docs (emphasis added):

The method will return the response instance with appropriate headers set. You should return the response instance from your action to prevent view rendering and let the dispatcher handle actual redirection.

This is also mentioned in the migration guide :

The signature of Cake\\Controller\\Controller::redirect() has been changed to Controller::redirect(string|array $url, int $status = null) . The 3rd argument $exit has been dropped. The method can no longer send response and exit script, instead it returns a Response instance with appropriate headers set.

Code example

The code in the question needs to be the equivalent of this:

public function editarImg($negocio_id=null){    
    if(!$this->Cookie->check('cookie')){
        return $this->redirect($this->referer()); # <- return the response object
    }

    // more code

Try this, it should work:

public function isCookieSet(){
  if(!$this->Cookie->check('cookie')){

    // return $this->redirect($this->referer()); <- not working

    $this->response = $this->redirect($this->referer());
    $this->response->send();
    exit;

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM