Slim-PHP: How to merge array into slim request

311 Views Asked by At

I'm creating a middleware for XSS protection in Slim framework. Here is my code:

$input = $request->getParsedBody();
    array_walk_recursive($input, function(&$input) {
        $input = htmlspecialchars($input);
    });
    $request->merge($input); // Not able to merge $input into $request

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

After sanitizing the request I wanted to merge into slim http request so that when I use $request->getParsedBody(), I should get the sanitize data.

1

There are 1 best solutions below

0
On
use Slim\Factory\AppFactory;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Psr7\Response;

require __DIR__ . '/vendor/autoload.php';

$app = AppFactory::create();

$app->post('/merge-array', function (Request $request, Response $response, $args) {
    // Get the current request body
    $body = $request->getParsedBody();
    
    // Your array to merge into the request body
    $newData = [
        'key1' => 'value1',
        'key2' => 'value2',
    ];

    // Merge the new data with the existing request body
    $mergedBody = array_merge($body, $newData);

    // Create a new request with the merged body
    $newRequest = $request->withParsedBody($mergedBody);

    // Forward the new request to the next middleware or route handler
    return $handler->handle($newRequest);
});

$app->run();

Try this code. Hope it will work,

$input = $request->getParsedBody();
array_walk_recursive($input, function(&$value) {
    $value = htmlspecialchars($value);
});

$newRequest = $request->withParsedBody($input);

return $next($newRequest, $response);