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

Redirects - am i doing something wrong?

Hey guys, i want to have a method which i can reuse in certain situations (code below). The idea is this method to redirect to login in some of the cases. My problem is that after i redirect the rest of the code is executed, which i think is unwanted behaviour, correct me if im wrong. Thanks in advance.

PHP version: 5.5.23 / Phalcon: 2.0.3

public function indexAction()
{
    $this->checkSomething();
    // Problem here..
    die('i should not be able to see this');
}

function checkSomething()
{
    // some logic here, whatsoever
    return $this->response->redirect('users/login');

    // some more logic here
}


574
Accepted
answer
$this->response->redirect('users/login');

This only sets the response, it doesn't actually send it. See https://docs.phalcon.io/en/latest/reference/response.html

The response is sent after the Action-function returns. But I think you could send the response by using

$this->response->send();

I don't quite understand what you need but I bet you try this;

     $this->dispatcher->forward(array( "controller" => "users", "action" => "login"));

Hi,

You must return the response in the Action :

public function indexAction()
{
    return ($this->checkSomething());
    // Problem here..
    die('i should not be able to see this');
}
edited Jun '15

Hello, thanks for your time guys!

@nobodypb - adding send() after the redirect did the job.

@DominicKinyanjui - I needed redirect, not a forward. As i said at some point user has to be redirected to new page with different url.

@MaxPRUDHOMME - i dont want to make the redirect in the action, because the idea of this function is to be reused in other methods/controllers.