Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Redirection from within action is not working

// THIS IS FROM loginController.php

    public function loginUserAction()  
    {  
        $loginObj = FT\LoginFactory::CreateLogin("RegularLogin");  

        $username  = $_POST["UserName"];  
        $password = $_POST["Password"];  

        if($loginObj->authenticateUser($username, $password))  
        {  
            $this->response->redirect("main/proceed");  

            // I've tried diffeent permutations of the following  
            // $this->view->disable();  
            // return false;  
        }  
        else{  
            throw new \Exception("Could not log in with provided credentials.");  
        }  
    }

// THIS IS FROM mainController.php

    public function proceedAction()  
    {  
        echo "<h2>This is the proceed Action</h2>";  
    }  

    public function route404Action()  
    {  
        echo "<h1>COULD NOT FIND EXPECTED ACTION/VIEW</h1>";  
    }

// THE EXPECTED RESULT IS:
"This is the proceed Action" -- (The echo from the "proceedAction")

// THE ACTUAL RESULT IS:
"COULD NOT FIND EXPECTED ACTION/VIEW" -- (The echo from the "route404Action")

// THE LIFE CYCLE OF THIS PROCESS after calling $this->response->redirect("main/proceed"):

It goes through the bootstrap "index.php" file in the "public" folder twice:

-- The first time of $application->handle->getContent() is: "This is the proceed action"

-- The second time is: "COULD NOT FIND EXPECTED ACTION/VIEW" and that is the end.

Any suggestion as to why it's doing this instead of just redirecting where it should?

What is the URL you're going to?



4.1k
edited Oct '14

I'm confused about your question since the redirect in the code I provided clearly states "main/proceed" (controller/action) pair. If you are refering the the address that will show up on the browser's address bar, then it will be http://[root]/[specific folder]/main/proceed.

Just to be complete, during the Dependency Injection object setup, the "url" service was setup as follows:

$di->set('url', function() {
       $url = new \Phalcon\Mvc\Url();
       $url->setBaseUri('/[specific folder]/');
       return $url;
});

Just to clarify, [root] and [specific folder] are fake names I posted here since I can't reveal their actual names due to work-related restrictions.

Are you using the default router or have you set up custom routes?



4.1k

Custom routes, however, the routing works correctly. If I type http://[root]/[specific folder]/main/proceed in the webrowser's address bar or I create a link with that controller/action pair, the desired page shows up correctly. It is only when I try to "redirect" that the issue described above shows up.

You say it's going through index.php twice? So does it appear that after the output from proceedAction is generated, a second redirection happens to the route404Action method? Or is this in one page load? Have you checked the headers that are being sent?

Have you tried exit() ing after proceedAction? That won't fix the problem, but may help you narrow down the culprit.



4.1k
edited Oct '14

Your first assertion is what is happening almost. My previous statement that it goes through index.php twice is incorrect. It actually goes through it three times.

The first time the output is a blank string. The second time the output from proceedAction gets echoed. The third time the output from route404Action gets echoed.

After putting exit(); at the end of the proceedAction, it goes through index.php twice. The first time, the output is an empty string, the second time is the output from route404Action.

It's just getting weirder.

It makes sense that it would go through twice - a redirection forces the browser to make a new request for the redirected page - so that's expected. What's weird is why, after proceedAction() gets processed, there's another redirection.

Maybe try installing an HTTP headers plugin in your browser and see what gets sent.



4.1k
edited Oct '14

Well, here is the output from fiddler:

**Result: 302; Protocol: HTTP;   Host:[host];   URL:/[Specific Folder]/loginUser (this is the action that does the redirecting)  **
HTTP/1.1 302 Found  
Date: Thu, 09 Oct 2014 16:20:59 GMT  
Server: Apache/2.4.4 (Win64) OpenSSL/1.0.1d PHP/5.4.12  
X-Powered-By: PHP/5.4.12  
Expires: Thu, 19 Nov 1981 08:52:00 GMT  
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0  
Pragma: no-cache  
Status: 302 Found  
Location: /[Specific folder]/main/proceed  
Content-Length: 0  
Keep-Alive: timeout=5, max=100  
Connection: Keep-Alive  
Content-Type: text/html; charset=UTF-8    


**Restult: 200;   Protocol: HTTP;   Host:[host];   URL:/[Specific folder]/main/proceed (expected restult)**  
HTTP/1.1 200 OK
Date: Thu, 09 Oct 2014 16:20:59 GMT
Server: Apache/2.4.4 (Win64) OpenSSL/1.0.1d PHP/5.4.12
X-Powered-By: PHP/5.4.12
Content-Length: 494
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

**Result:200;   Protocol:HTTP;  Host:[host];    URL;/[SPecific Folder]/index.html** (Not sure why it states this one since that file does not even exist)**   
HTTP/1.1 200 OK
Date: Thu, 09 Oct 2014 16:20:59 GMT
Server: Apache/2.4.4 (Win64) OpenSSL/1.0.1d PHP/5.4.12
X-Powered-By: PHP/5.4.12
Content-Length: 431
Keep-Alive: timeout=5, max=98
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

This is the output when you exit() out of the /main/proceed action? What if you don't - does /main/proceed send a 302 header?

My guess about index.html is its a default action of your browser for some reason. I wouldn't worry too much about that.



4.1k

No, the output above was without the exit() out of the /main/proceed action. Below is the output WITH the exit() at the end of the /main/proceed action:

**Result: 302; Protocol: HTTP;   Host:[host];   URL:/[Specific Folder]/loginUser (this is the action that does the redirecting)**  
HTTP/1.1 302 Found  
Date: Thu, 09 Oct 2014 18:44:50 GMT  
Server: Apache/2.4.4 (Win64) OpenSSL/1.0.1d PHP/5.4.12  
X-Powered-By: PHP/5.4.12  
Set-Cookie: PHPSESSID=mbaigefh5muvkm6jnilnls8gl5; path=/  
Expires: Thu, 19 Nov 1981 08:52:00 GMT  
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0  
Pragma: no-cache  
Status: 302 Found  
Location: /[Specific Folder]/main/proceed  
Content-Length: 0  
Keep-Alive: timeout=5, max=100  
Connection: Keep-Alive  
Content-Type: text/html; charset=UTF-8  

**Restult: 200;   Protocol: HTTP;   Host:[host];   URL:/[Specific folder]/main/proceed (expected restult)**  
HTTP/1.1 200 OK  
Date: Thu, 09 Oct 2014 18:44:51 GMT  
Server: Apache/2.4.4 (Win64) OpenSSL/1.0.1d PHP/5.4.12  
X-Powered-By: PHP/5.4.12  
Content-Length: 35  
Keep-Alive: timeout=5, max=99  
Connection: Keep-Alive  
Content-Type: text/html; charset=UTF-8  

**Result:200;   Protocol:HTTP;  Host:[host];    URL;/[SPecific Folder]/index.html**  
HTTP/1.1 200 OK
Date: Thu, 09 Oct 2014 18:44:51 GMT
Server: Apache/2.4.4 (Win64) OpenSSL/1.0.1d PHP/5.4.12
X-Powered-By: PHP/5.4.12
Content-Length: 431
Keep-Alive: timeout=5, max=98
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

I was probably wrong before - that "Route not found" is likely the result of the request to index.html. However, it doesn't make sense that that file be requested - unless there is something from the output of /main/proceed that is causing index.html from being requested.

The Content-Length header is really small when compared to the Content-Length of index.html. Makes me wonder what the actual content from /main/proceed/ is.

Do you have access to your server logs? What does the access log look like when you do this?



4.1k

For no exit() at end of /main/proceed , the server access log produces:

 [IP Address] - - [09/Oct/2014:11:40:14 -0700] "POST /[Specific Folder]/login/loginUser HTTP/1.1" 302 -  
 [IP Address] - - [09/Oct/2014:11:40:14 -0700] "GET /[Specific Folder]/main/proceed HTTP/1.1" 200 494  
 [IP Address] - - [09/Oct/2014:11:40:15 -0700] "GET /[Specific Folder]/login/index.html HTTP/1.1" 200 431

For exit() at end of /main/proceed

[IP Address]- - [09/Oct/2014:11:44:50 -0700] "POST /[Specific Folder]/login/loginUser HTTP/1.1" 302 -  
[IP Address] - - [09/Oct/2014:11:44:51 -0700] "GET /[Specific Folder]/main/proceed HTTP/1.1" 200 35  
[IP Address] - - [09/Oct/2014:11:44:51 -0700] "GET /[Specific Folder]/login/index.html HTTP/1.1" 200 431

The actual output from the /main/proceed is:

echo "<h2>This is the proceed Action</h2>";

What if you disable the view before the redirect in /login/loginUser, and exit() after the redirect? I remember reading somewhere that calling a redirect doesn't stop the rest of the output from being generated - maybe the /login/loginUser method is causing the /login/index.html request? Grasping at straws at this point.



4.1k

That process does not go through the redirection at all. It goes through the boostrap index.php just once and the end result is the route404Action;

Fiddler output and access logs show the correspoding data (IE, POST to /login/loginUser, then GET to index.html)

Given the fact that the Phalcon::Tag->linkTo([....]) components are working correctly, that any hardcoded link in the form of (http://[root]/[Specific Folder/controller/action) and any properly-typed address in the browser address bar all work correctly, is it possible that there is a rogue Phalcon configuration in my system that may be causing redirection to fail (mind you that it is mostly a default configuration, the only changes I made when compared to the 'Album-o-rama' sample project are the ones to the 'routing' but those I've already explained above and their failure would also affect the linkTo Tags)?

I don't know of any Phalcon project setting one can make to force an action to redirect. We've exhausted my troubleshooting expertise - maybe someone like @Phalcon has some more insight.



4.1k

I've seen his gravatar in other recent posts. Do I have to pay him to come to this one, or should I just put his name in all caps???? Pulling my hair out here, just trying to laugh a little.

I don't know of any Phalcon project setting one can make to force an action to redirect. We've exhausted my troubleshooting expertise - maybe someone like @Phalcon has some more insight.

The @ mention like I did is about all one can do.



82.2k

1) Change this:

$this->response->redirect("main/proceed");

To

return $this->response->redirect("main/proceed");

2) Add a favicon.ico to your document root, sometimes this causes a request to being accessed twice

3) This could be likely a problem with your router or the base uri registered in Phalcon\Mvc\Url component



4.1k
edited Oct '14

Changed the code to the suggestion above and added the favicon.ico file. The result remains the same.

Here is the routing code I'm using. The "baseUri" code is already described in one of the replies above.

    $router->add('', array(
        'module' => 'User',
        'namespace' => '[Specific Folder]\User\Controllers\\',
        'controller' => 'main',
        'action' => 'main'
    ));

    $router->add('/', array(
        'module' => 'User',
        'namespace' => '[Specific Folder]\User\Controllers\\',
        'controller' => 'main',
        'action' => 'main'
    ));

    $router->add('/:controller', array(
            'module' => "User",
            'namespace' => '[Specific Folder]\User\Controllers\\',
            'controller' =>1,
            'action' => 1
        ));

    $router->add('/:controller/:action', array(
            'module' => "User",
            'namespace' => '[Specific Folder]\User\Controllers\\',
            'controller' =>1,
            'action' => 2
        ));

    $router->notFound(array(
        'module' => 'User',
        'namespace' => '[Specific Folder]\User\Controllers\\',
        'controller' => 'main',
        'action' => 'route404'
    ));

    return $router;


82.2k

When you say: [Specific Folder] is that really a folder? I mean, it must be a namespace loadable via Phalcon\Loader or similar.



4.1k

Not really a folder. The [Specific folder] i've been providing is just placeholder for the purposes of this thread, since I'm not allowed by my company to reveal the name yet.

I used that placeholder ([Specific Folder]) as the root of the namespaces I'm using (because the actual name is the name of the project), ie:

namespace [Specific Folder]\User\Controllers
namespace [Specific Folder]\Library\Common\Helpers
etc.....

Also for the baseUri (because the it is also the name of the base folder for this project):

`$di->setBaseUri('/[Specific Folder]/');`

Now, since creating a link via the "Phalcon::Tag->linkTo('[controllername]/[actionname]')" works 100% of the time, and typing an appropriate address on the browser's address bar works 100% of the time, I would assume that routing and namespaces are actually working correctly, and the fact that I've added the favicon.ico in the correct place and added "return $this->response->redirect("main/proceed")" as suggested, what other things could possibly be causing the redirection process to behave this way?



82.2k

If you want to upload the relevant parts to a repository, I could clone it and take a look



4.1k

Thanks. It will take me a bit because I have to set up a bitbucket account first. I'll post the link here when ready.



82.2k

I've cloned the repo, when I access: http://localhost/phalconredirecttest/login/loginUser

It redirects to: http://localhost/phalconredirecttest/main/proceed

What is the expected behavior?



4.1k

Initial load of website should go to ... index.php

Clicking on the "Login Redirection Test" link shold bring you to the "login/login" page providing anyting for the "User Name" / "Password" texboxes and clicking the "Login" button should redirect you "main/proceed" but it doesnt, it acuallytakes you to "login/index.html" why? I don't know.

Clicking on the "Proceed Link Test" link, takes you to "main/proceed" as expected

Typing http://localhost/PhalconProjectForForum/main/proceed in the web browser address bar takes you to "main/proceed" as expected.

So the only thing failing is the redirection that is occurring inside the code of "login/loginUser". That redirection should take you to "main/proceed", but it doesn't.



82.2k

When I click the login button it does not makes anything because of Javascript errors:

GET http://localhost/PhalconEnhancedWebpages/public/ui/kendo/styles/kendo.common.min.css  (index):5
GET http://localhost/PhalconEnhancedWebpages/public/ui/kendo/styles/kendo.black.min.css  (index):5
GET http://localhost/PhalconEnhancedWebpages/public/ui/css/common/info.css  (index):5
GET http://localhost/PhalconEnhancedWebpages/public/ui/css/common/common.css  (index):5
GET http://localhost/PhalconEnhancedWebpages/public/ui/kendo/js/jquery.migrate.js  (index):5
GET http://localhost/PhalconEnhancedWebpages/public/ui/kendo/js/jquery.min.js  (index):5
GET http://localhost/PhalconEnhancedWebpages/public/ui/kendo/js/kendo.all.min.js  (index):5
Uncaught ReferenceError: $ is not defined (index):6(anonymous function)

Not sure if there are missing files in the repository



4.1k

You should replace PhalconEnhancedWebpages with PhalconProjectForForum



82.2k
Accepted
answer

You have this function:

function loginSuccessFunction(data, textStatus, jqXHR)
{
            // it should never get here since a successful login means redirection to the index.html page
            // ...... unless the call was made via ajax.  If so, a successful function will return here and we should redirect to index.html.
            window.location = "index.html";
}

Which makes a redirection after the ajax operation is successfully complete, that's why you see /login/index.html in the browser's url



4.1k

Im such a tool!!! Rampant copy and paste... Sorry for getting youinvolved In this troubleshooting excercise. :-(