Middleware influence on body


#1

When I use middleware to remove stuff out of the generated content, my html is wierd.

Example:

public function __invoke($request, $response, $next)
{
	$response = $next($request, $response);
    $response->getBody()->rewind();
    $response->getBody()->write("change the html");
    
    $content = (string)$response->getBody();
    var_dump($content);
    die();

    return $response;
}

What happens is that the first characters of my HTML are the canged ones, but the rest of the HTML is my old HTML. (I think it’s because the string length is allready set.)

I can expand the body with success, but never shrink it, which is wierd.

So I’m looking for a solution…


#2

Hello @marcelloh

Ok let’s take this example:

$response->getBody()->write("1234567890");
$response->getBody()->rewind();
$response->getBody()->write("x");

$content = (string)$response->getBody();
echo $content;

The result is not "x" it’s "x234567890"!

Is this what you mean? The reason behind this is a so called stream. The rewind method just changes the offset in the stream to the first position, but it does’t clear the previous content in the stream.

To replace the whole content try this instead:

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

$stream = fopen('php://memory', 'r+');
fwrite($stream, 'new content');
rewind($stream);

return $response->withBody(new \Slim\Http\Stream($stream));

#3

I changed this into your proposol, and it works. (never noticed it was a stream)
:smile: Thanks