We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Redirect with status doesn't work

Hello !

I want to redirect to a login page if the user is not logged in (seems logic).

But when I try to add a status to the redirection, it doesn't work.

First try

I want to redirect in the beforeExecuteRoute. So I tried this (according to this thread) :

return $this->dispatcher->setReturnedValue($this->response->redirect("user/login", false, 401));

and this

$this->dispatcher->setReturnedValue($this->response->redirect("user/login", false, 401));
return false;

In both cases, Curl displays a 401 status (good), but the page stays to the current page and doesn't redirect to /user/login (bad)

Second try

$this->response->setStatusCode(401, "Unauthorized");
return $this->response->redirect("user/login");

Here, Curl displays a 302 status (bad), but the page redirect correctly to /user/login (good)

Third try

return $this->response->redirect("user/login", false, 401);

Here I got the same results as the first try...


So, how can I have a 401 redirect status with Curl and that my page redirect to /user/login too ?

Anyone has the same problem ?

By the way : I'm using Nginx and php-fpm, debian7, and I'm using phalcon 1.3.4 (no phalcon 2 for the moment).

PS : I apologize for my English.



6.4k
Accepted
answer

You can't redirect with a 401 status header, 4** codes are not made for redirection, instead use a 3** header. Moreover in your case would be more appropriate send a non authorized header and then redirect with JavaScript.


    $this->response->setStatusCode('401', 'Unauthorized');

    $url = $this->url->get('user/login');

    $this->dispatcher->setReturnedValue(<<<HTML
<!DOCTYPE html>
<html>
    <head>
        <meta name=robots content=noindex>
        <meta http-equiv=refresh content="0;URL='{$url}'">
    </head>
    <body>
        <script>
        setTimeout(function () {
            window.location.href='{$url}';
        }, 1e3);
        </script>
    </body>
</html>
HTML
);

Hi !

Ok then, I will use 3XX redirect only. I thought it was possible...

I tried the redirect by javascript but it didn't work.

Thanks for your help !