繁体   English   中英

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

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

我为纤薄的 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);
        }
    };
}

发生的情况是,如果我尝试将它插入到这样的路径中:

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

echoRes函数

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

发生的情况是,即使未通过身份验证,它也会继续给我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();
        }
    };
}

我使用 $app->notfound() 或 $app->halt(403) 来停止执行。 不需要设置状态代码,因为它是由这些功能设置的。

如果您碰巧使用的是 2.2.0 版本(我不确定是否适用于更高版本)并且还必须在设置 403 响应状态后添加 JSON 响应,那么您可以使用$app->stop() 使用$app->halt(arg)删除正文的内容。

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

你需要使用 ->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