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

Response redirect in micro app not working

Hi,

Can you tell me why the $app->response->redirect("/"); is not working? It executes the code when there is no session but never redirects. It never sends a response.

Please help!

$eventManager->attach('micro', function($event, $app) {

    if ($event->getType() == 'beforeExecuteRoute') {
        if ($app->session->get('auth') == false) {

            $app->response->redirect("/");

            //Return (false) stop the operation
            return false;
        }
    }

});

Thanks, Stefano



58.4k
edited Oct '14

@MaskPZ

if ($app->session->get('auth') == false) {
    return  $app->response->redirect("/");
}


3.3k
edited Oct '14

Hi @duythien,

Thanks for your answer but it does not work. If I don't return false, the original request remains alive and it's like I've never checked the session. Here it's the original code (copy&paste from the official documentation):

<?php

use Phalcon\Mvc\Micro,
    Phalcon\Events\Manager as EventsManager;

//Create a events manager
$eventManager = new EventsManager();

//Listen all the application events
$eventManager->attach('micro', function($event, $app) {

    if ($event->getType() == 'beforeExecuteRoute') {
        if ($app->session->get('auth') == false) {

            $app->flashSession->error("The user isn't authenticated");
            $app->response->redirect("/");

            //Return (false) stop the operation
            return false;
        }
    }

});

$app = new Micro();

//Bind the events manager to the app
$app->setEventsManager($eventManager);

It should work, I really don't know why it does not redirect. Any ideas???

Thanks, Stefano



3.3k
Accepted
answer

[UPDATE - SOLUTION]

Check this code out: https://github.com/cmoore4/phalcon-rest/blob/develop/index.php

I've solved using the same logic of the commented begin handler in the above code. It's does not fix the response not working but it's what I needed. Hope it can help someone else.