【问题标题】:Slim Framework PHP - block routes access to users in some conditionsSlim Framework PHP - 在某些情况下阻止对用户的路由访问
【发布时间】:2016-08-20 22:55:22
【问题描述】:

我正在为 PHP 使用 Slim Framework v3,这是我在类中用于创建我的 API 的代码:

public function __construct( ) {
    $this->slim = new \Slim\App;
    $this->init();
    $this->slim->run();
}

private function init () {
    $this->slim->add(function ($request, $response, $next) {
        // my code ...
        return $response;
    });
    $this->slim->get('/getElements', array($this, 'getElements'));
    $this->slim->get('/getElements2', array($this, 'getElements2'));
    // and more...
}

public function getElements ( $request, $response, $args ) {
    // my code ...
}

public function getElements2 ( $request, $response, $args ) {
    // my code ...
}

在某些情况下,我需要限制用户访问 API,因此在上述情况下,当他们尝试访问应用程序路由时,我需要返回带有错误的 response。 因此,用户在尝试访问getElementsgetElements2 和所有其他路由时会收到错误消息。

我一直在考虑在init() 函数中添加一些代码并在那里阻止用户,但是我可以使用什么代码来做到这一点?

另外,另一种方法是为每个路由回调添加一些代码并执行以下操作:

public function getElements ( $request, $response, $args ) {
   echo json_encode(array(
      'error' => array(
         'msg' => "MESSAGE...",
      ),
   ));
   return $response;

   // my code ...
}

但我有很多路线,我宁愿避开。

有什么想法吗?

编辑:我忘了提到在决定是否应该阻止用户之前我需要访问$request 对象。

谢谢

【问题讨论】:

标签: php slim


【解决方案1】:

我刚刚通过这样做解决了:

if ( !$check ) {
  return $response->withStatus(403);
}

在我的$this->slim->add() 函数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2020-05-08
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    相关资源
    最近更新 更多