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

Issuing redirect form a component

Hi,

I have a component which handles some auth and other checks.

Auth extends Component { public function getUser() { // if user is valid then return details return ...; // if the user is not valid or some conditions do not meet then $this->response->redirect($loginpage); } }

MyController extends Controller { public myAction() { $u = $this->auth->getUser(); // do something with $u } }

In case the user is valid, I want the processing to continue in the action. If the user is not valid, getUser() will issue a redirect, but the processing in myAction() continues after the return from getUser().

I want the processing in myAction() to stop if the user is not valid.

One option is to return Null from getUser() and do something like following in myAction(), but I would like to avoid this.

public myAction() { $u = $this->auth->getUser(); if ($u == null) return; }

I also tried exit() after issuing the redirect but get a blank page.

This is more of a PHP question rather than a Phalcon one. Any help appreciated.

Regards!



7.3k

Ok, found it. Following line alone is not sufficient.

$this->response->redirect('...');

Need to change it to:

$this->response->redirect('....'); $this->response->send();

Regards!



98.9k

Send the response inside a controller is not recommended because it will be sent twice, you must return the response from the controller:

return $this->response->redirect('....');

or

$response = new Phalcon\Http\Response();
$response->redirect('...');
return $response;
edited Jun '14

@hkun Thank you for sharing the solution. send() works for me :)