Want to PHP trim() body, query parameters, and arguments

I’d like to trim all incoming data, whether it be in the body, a query parameter, or argument (route placeholder).

A middleware seems to be the best place to do this work. I searched online but couldn’t find any existing code, so I wrote this:

// Middleware to sanitize (trim) all incoming data
$app->add(function (Request $request, Response $response, callable $next) {

    // Trim any data in the body
    $body = $request->getParsedBody();
    // Make sure the body has some data before we try to trim it
    if (is_null($body) === false) {
        // Pretty basic sanitizing - right now just trimming the values
        $body = filter_var($body, FILTER_CALLBACK, ['options' => 'trim']);

        // Replace the posted body with the cleaned copy
        $request = $request->withParsedBody($body);
    }

    // Trim any data in the query parameters
    $query_params = $request->getQueryParams();
    // Make sure the query params have some data before we try to trim them
    if (is_null($query_params) === false) {
        // Pretty basic sanitizing - right now just trimming the values
        $query_params = filter_var($query_params, FILTER_CALLBACK, ['options' => 'trim']);

        // Replace the posted query parameters with the cleaned copy
        $request = $request->withQueryParams($query_params);
    }


    // And finally, trim the arguments, if any
    $route = $request->getAttribute('route');
    $arguments = $route->getArguments();
    if (is_null($arguments) === false) {
        // Pretty basic sanitizing - right now just trimming the values
        $arguments = filter_var($arguments, FILTER_CALLBACK, ['options' => 'trim']);

        // Replace the arguments with the cleaned copy
        $route->setArguments($arguments);
    }

    // Go on to the next callable
    $response = $next($request, $response);

    // We're all finished
    return $response;
});

Thoughts?

I think it’s quite expensive to prepare every request like this. Have you checked the performance?
Some none string values could get lost: https://3v4l.org/VW0bS
In some special cases, for example in the CLI, there is no request object. Then you must trim the data in another layer of the application.

I do not recommend this.

  • 99% of requests will not need this
  • in future, I guarantee to you, that you will find use-case in your app (whatever you are doing) where the white-space in query parameter will be missed
  • if your business logic require this “trim” , do it in you business model layer, it is better approach (you can reuse your business layer with trim for example for CLI app)
  • performance will be affected without quesitons