Slim 框架是否为 POST 方法提供了 URL 编码注释?

does Slim framework have URL encoded annotation for POST method?

我正在使用 php.I 的 slim 框架开发 Web RESTful API 想知道如何在 POST 方法上添加一些注释类型的东西,以便它可以表现为 URL 编码 method.Please 在这方面帮助我 regard.Advance 谢谢。

没有针对此的预编程方法 - 没有 Slim 或 php 方法可以明确检查您的字符串是否经过 urlencoded。你可以做的是在你的路由中实现 Slim Middleware。

<?php
$app = new \Slim\App();

$mw = function ($request, $response, $next) {
    if ( urlencode(urldecode($data)) === $data){
      $response = $next($request, $response);
    } else {
      $response = ... // throw error
    }

    return $response;
};

$app->get('/', function ($request, $response, $args) { // Your route
    $response->getBody()->write(' Hello ');

    return $response;
})->add($mw); // chained middleware

$app->run();

讨论:Test if string is URL encoded in PHP

中间件:https://www.slimframework.com/docs/v3/concepts/middleware.html

由于您使用 Slim 作为 API 的基础,最简单的方法是只构建一个定义了所需 URL 参数的 GET 路由:

$app->get('/users/filter/{param1}/{param2}/{param3}', function (Request $request, Response $response) {
    // Route actions here
});

在您的文档中,确保告知此 API 的使用者它是一个 GET 端点,因此不应创建 POST 正文;相反,您在 URL 中概述的参数应该用于将客户端的数据传递给 API。

如果您打算使用仅带有 URL 参数的 POST 路由,那么如果路由检测到传入的 POST 正文,您也可以强制返回响应:

$app->post('/users/filter/{param1}/{param2}/{param3}', function (Request $request, Response $response) {

    $postBody = $request->getParsedBody();

    if (is_array($postBody)) {

        $denyMsg = "This endpoint does not accept POST body as a means to transmit data; please refer to the API documentation for proper usage.";
        $denyResponse = $response->withJson($denyMsg, $status = null, $encodingOptions = 0);

        return $profileData;

    }
});