Modify parameters and arguments with Middleware



I need to transform everything that comes from GET, POST, PUT, DELETE and the arguments of the url in base64.

I have the following example script, I can not understand how it should be done.

    namespace Api\Src\Middleware;

    use Psr\Http\Message\ServerRequestInterface as Request;
    use Psr\Http\Message\ResponseInterface as Response;

    class Base64Middleware
        public function __construct()
        public function __invoke(Request $request, Response $response, $next)
            // 1. TODO: All parameters sent by GET, POST, PUT or DELETE must be encoded in base64
            $arrParams = $objRequest->getParams();

            $arrEncodeParams = $this->encodeBase64($arrParams);

            // How should I send it?
            $request = $objRequest->withParams($arrEncodeParams);

            // 2. TODO: Every argument sent by the url must be encoded in base64
            // $app->get('/foo/{code}', ...)
            $arrAttributes = $request->getAttributes();

            $arrEncodeAttributes = $this->encodeBase64($arrAttributes);

            // How should I send it?
            $request = $request->withAttributes($arrEncodeAttributes);

            $response = $next($request, $response);
            return $response;

        private function encodeBase64($arrParams)
            foreach ($arrParams as $key => $itemParam) {
                if (empty($itemParam) || !is_string($itemParam)) {
                $strEncodeParam = base64_encode($itemParam);
                $arrParams[$key] = $strEncodeParam;

            return $arrParams;


What you need is a method that changes the request , something like this:

protected function getRequestWithEncodedAttributes(Request $request)
      $attributes = $request->getAttributes();
       foreach($attributes as $name => $value) {
           $request = $request->withAttribute($name, base64_encode($value)); 
       return $request;

You should do the same for the $request->getParams();



The problem is that I don’t know how.



For posted values you can use : $request = $request->withParsedBody($encodededParsedBody);
And for get values: $request = $request->withQueryParams($encodededQueryParams);

1 Like