Slim 3.0 Redirect Not working

I’m not sure what is going on here. I swear I had the redirect working before, but now it isn’t.

Relevant Namespaces:
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

Initialization and container:

	$app = new \Slim\App(["settings" => $config]);

// Fetch DI Container
$container = $app->getContainer();

// Register Twig View helper
$container['view'] = function ($c) {
    $view = new \Slim\Views\Twig($_SERVER['DOCUMENT_ROOT'].'/Feedback/templates', [
        'cache' => false
    ]);
    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $c['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($c['router'], $basePath));

    return $view;
};

Here’s the redirect:

	$app->get('/test', function (Request $request, Response $response) {

        $url =  $this->get('router')->pathFor('dashboard');

        return $response->withStatus(302)->withHeader('Location', $url);
    });

Can someone please help me figure this out.

After almost 3 hours of scratching my head, I finally figured it out. I had put the following code at the top of my index.php file:

	echo "Initial: ".memory_get_usage()." bytes \n";
    echo "Peak: ".memory_get_peak_usage()." bytes \n";

I’m just curious, why does this break the redirect? I’m guessing it’s because an output is written to the page before the redirect is initiated. Kind of like PHPs output buffer.

Exactly this. A redirect is an HTTP header and you can’t send an HTTP header after you’ve started sending the HTTP body (via echo).

Put your memory debugging messages into middleware and attach to the $response and you’ll be fine.