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

Wrong redirect because response->redirect prefix internal urls with "/"

Hi! i've this problem in my MVC App.

i have base uri of the Url service set to "/"

now, if i generate an URI with the Url service for a specific action, the generated relative uri is correct. put the result is php $red="/aa/bb";

but when i use $this->response->redirect($red) the redirect fail as it set a wrong location header, infact i can see it set "location: //aa/bb" (note the double initial slash)

Actually i can't use the automatic url generation of the response->redirect method as i need to add a querystring to the redirect URL so i need to pass a string that is a relative url to my website just like "/aa/bb?params=1".

Solutions?

PS. It would be nice in the next version of Phalcon 1.x to have some method or implicit mechanism to add querystring to urls generated by the Url service. For example in .NET all parameters that do not match the named route are automatically added as querystring in the url generated.



17.8k
Accepted
answer

PS2. actually i've solved implementing this method in my BaseController:

    /**
     * Fixed redirect method for internal urls generated by the Url service
     * @param string $uri
     */
    public function redirect($uri) {
        if (strpos($uri,"/")===0) {
            $uri=substr($uri,1);
        }
        $this->response->redirect($uri,false);
    }

But it would be great to have a more elegant way usable anywhere...



98.9k

Any URI passed to $this->response->redirect is also processed by the URL service, that's why the / is prepended to any parameter passed to it.

$this->response->redirect($uri); == header("Location: " . $this->url->get($uri));


309

Or you can just use the second parameter, that will treat the url as an external one, and don't process it:

$this->response->redirect($this->url->get('/test/', array('param1' => 'test'), true);

I've just used it because redirect doesn't accept query-string parameters (second parameter of $this->url->get()).