Search code examples
phpcodeignitercodeigniter-4

CodeIgniter 4 Filter - exit with response


I have a project with CodeIgniter 4.

I have a before filter:

public function before(RequestInterface $request){

    $auth = $request->getHeader("Authorization");
    if($auth == null){

        $response = Services::response();
        $response->setStatusCode(401);
        $response->setHeader("WWW-Authenticate", "Bearer Token");
        $response->setBody("{\"error\": \"unauthorized\"}");

        exit;

    }

}

If there is no authorization, I want to stop the request and return $response to client.

Right now the request is stopped, because of exit.

But as answer I get 200 OK and without body content.

How I can exit the request and set that $response to client?


Solution

  • As mentioned in the comment, returning a Response object in the before method of a Filter prevent the execution of the controller. You don't need to use die or exit.

    public function before(RequestInterface $request){
    
        $auth = $request->getHeader("Authorization");
        if($auth == null){
    
            $response = Services::response();
            $response->setStatusCode(401);
            $response->setHeader("WWW-Authenticate", "Bearer Token");
            $response->setBody("{\"error\": \"unauthorized\"}");
    
            return $response;
    
        }
    
    }
    

    Note that returning nothing with return; won't stop the controller from running.