【发布时间】:2019-10-19 22:30:35
【问题描述】:
我正在使用 php 的苗条框架开发一个 web RESTful API。我想知道如何在 POST 方法上添加一些注释类型的东西,以便它可以作为 URL 编码方法。请在这方面帮助我。Advance谢谢。
【问题讨论】:
我正在使用 php 的苗条框架开发一个 web RESTful API。我想知道如何在 POST 方法上添加一些注释类型的东西,以便它可以作为 URL 编码方法。请在这方面帮助我。Advance谢谢。
【问题讨论】:
对此没有预先编程的方法 - 没有 Slim 或 php 方法可以明确检查您的字符串是否是 urlencoded。您可以做的是在您的路由中实施 Slim 中间件。
<?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;
}
});
【讨论】: