legomolina
legomolina

Reputation: 1083

Catching status code from redirect in Slim v3

I have a view that sends a form to another route and this checks that all data in form is correct but if aren't, this route (/check) must redirect to the view with the form (/form) with the code XXX so I can catch this code and I can know where is the problem (incorrect data, form not filled ...). The problem is that $response->getStatusCode(); also returns 200.

Routes show like this:

$app->get('/form', function($request, $response, $arguments) {  
    $error = array("error" => false);
    echo $response->getStatusCode(); //Always print 200

    if($response->getStatusCode() == XXX) 
        $error["error"] = true;

    return $this->view->render($response, "form.php", $error);
});

$app->post('/check', function($request, $response, $arguments) {
    return $response->withHeader('Location', '/form')->withStatus(403);    
});

Upvotes: 2

Views: 419

Answers (1)

jmattheis
jmattheis

Reputation: 11125

The responsecode is from the current response so it is default 200, when you not change it in the current route. The response object get created in every request, so it doesn't save the values you entered before.

You could take it like that

  • Client request /check
  • Server response with a redirect and 403
  • Client redirects and requests /form
  • <-- here you are now, you cannot know the 403 status code in the redirect.

You may use url parameters like ?error=true, a session or cookies.

OR:

Dont redirect and add the post also to /form and validate it there.

Upvotes: 2

Related Questions