简体   繁体   English

Slim php,在一个小的中间件中发送403响应状态码后,停止,死掉

[英]Slim php, stop, die after sending a 403 response status code in a small middleware

I created a small middleware function for slim php framework that checks if the user is authenticated or not, like so.我为纤薄的 php 框架创建了一个小的中间件函数,用于检查用户是否通过身份验证,就像这样。

function authenticate($app) {
    return function() use ($app) {
        if (!isset($_SESSION['user'])) {
            $response = array();
            array_push($response, array(
                    'error' => true,
                    'message' => 'You are not logged in.'
                )
            );
            echoRes(403, $response);
        }
    };
}

What happens is that if I tried to insert it in a route like this:发生的情况是,如果我尝试将它插入到这样的路径中:

$app->get('/', authenticate($app), function() use ($app){
     echoRes(200, 'hello world!');
});

The echoRes function echoRes函数

function echoRes($code, $response) {
    $app = \Slim\Slim::getInstance();
    $app->status($code);
    $app->contentType('application/json');
    echo json_encode($response);
}

What happens is that it will continue to give me a status code of 200 even when not authenticated, even I kill it using die() ;发生的情况是,即使未通过身份验证,它也会继续给我200的状态代码,即使我使用die()杀死它;

function authenticate($app) {
    return function() use ($app) {
        if (!isset($_SESSION['user'])) {
            $response = array();
            array_push($response, array(
                    'error' => true,
                    'message' => 'You are not logged in.'
                )
            );
            echoRes(403, $response);
            die();
        }
    };
}

I use $app->notfound() or $app->halt(403) to halt execution.我使用 $app->notfound() 或 $app->halt(403) 来停止执行。 There is no need to set the status code as it is set by these functions.不需要设置状态代码,因为它是由这些功能设置的。

If you happen to be using version 2.2.0 ( I'm not sure if applicable in higher version ) and also have to add JSON response after setting 403 response status, then you may use $app->stop() .如果您碰巧使用的是 2.2.0 版本(我不确定是否适用于更高版本)并且还必须在设置 403 响应状态后添加 JSON 响应,那么您可以使用$app->stop() Using $app->halt(arg) removes the contents of the body.使用$app->halt(arg)删除正文的内容。

With Slim 3.0, halt() and stop() does not exists anymore.在 Slim 3.0 中,halt() 和 stop() 不再存在。 Reference: http://www.slimframework.com/docs/v3/start/upgrade.html#removal-of-stophalt参考: http : //www.slimframework.com/docs/v3/start/upgrade.html#removal-of-stophalt

You need to use ->withJson():你需要使用 ->withJson():

return $response->withJson([
  'error' => true,
  'message' => 'You are not logged in.'
], 403);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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