PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 24, 2022

[FIXED] CodeIgniter 4 Filter - exit with response

 March 24, 2022     codeigniter, codeigniter-4, php     No comments   

Issue

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.



Answered By - ViLar
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing