Unable to redirect after post


#1

Hi there,
I’m new to Slim, so please be kind if my question seems dumb to you.
Here is the content of my file test.php:

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';

$app = new \Slim\App(['settings' => $config]);
$container = $app->getContainer();

$app->get('/test', function(Request $request, Response $response){
    $response->getBody()->write('<form method="POST"><input type="submit"></form>');
    return $response;
})->setName('test');

$app->post('/test',function(Request $request, Response $response) {
    $response->withRedirect($this->router->pathFor('test'),303);
    return $response;
});

$app->run();

So, when I open my browser on http://localhost:8000/test.php/test (served with the command php -S localhost:8000), the expected single submit buttons appears. When I click it, I expect my browser to be redirected on the same page with http status 303, but the only thing I get is a status 200 and empty page.

What have I done wrong ?


#2

Try a 302 header instead.


#3

Try to rename ‘test.php’ to ‘index.php’ and then use this url: http://localhost:8000/test


#4

@SVL Do you mean to change this line:

$response->withRedirect($this->router->pathFor('test'),303);

to this:

$response->withRedirect($this->router->pathFor('test'),302);

?
I tried, it do not change anything, and I wonder why it should…


#5

@odan I tried, but it does not fix the problem.
I think that there is no routing problem, because, the two routes work as expected. It just the redirection that did not work. All treatments are done, but the redirection. I’m stuck in the post route. I can reload the page, the form is submitted again.


#6

Ok I have tested it on my computer. This should work:

$app->post('/test',function(Request $request, Response $response) {
    $response = $response->withRedirect($this->router->pathFor('test'),303);
    return $response;
});

#7

@odan You’re right ! That’s it! Thanks for your help !