簡體   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