createAbsoluteUrl generates a path-like URL, how to avoid it?

php, url, yii

Solution

You need to specify that the `urlManager` application component should use the "get" format for the URLs it generates; the default is to use the "path" format. The Yii guide explains how to do it inside your application configuration:

array(
    ......
    'components'=>array(
        ......
        'urlManager'=>array(
            'urlFormat'=>'get',
        ),
    ),
);

Update: So your `urlFormat` is "path" and that's by design... what about alternatives?

If you don't mind extending `CWebApplication` and using your own derived class in its place then you have several options such as:

Define your own `createUrlEx` method based on the original `createUrl`. It could look like this:

public function createUrlEx($format,$route,$params=array(),$ampersand='&')
{
    $oldFormat = $this->getUrlManager()->getUrlFormat();
    $this->getUrlManager()->setUrlFormat($format);
    $url = $this->getUrlManager()->createUrl($route,$params,$ampersand);
    $this->getUrlManager()->setUrlFormat($oldFormat);
    return $url;
}

Override `registerCoreComponents` so that you can have a second url manager:

protected function registerCoreComponents()
{
    parent::registerCoreComponents();

    $components=array(
        'specialUrlManager'=>array(
            'class'=>'CUrlManager',
            'urlFormat'=>'get',
        ),
    );

    $this->setComponents($components);
}

You can now call `Yii::app()->specialUrlManager->createUrl(...)` anytime.

You can also approach the problem in other ways:

Extend `CUrlManager` and expose a method that allows you to select the flavor of url to create on the spot.

If you only need "get" urls in one or two places, you can always create a new `CUrlManager` object, configure it on the spot, call `createUrl` and then discard it. You could also hide this ugliness behind a free function. Essentially this (admittedly not recommended) approach is a low-tech version of the first workaround given that has the advantage that you don't need to extend `CWebApplication`.

Problem

I create a URL like this: ``` $app->createAbsoluteUrl('/', array( 'param1' => 'val1', 'param2' => 'var2', ); ``` The generated URL is: ``` http://mysite.com/param1/var1/param2/var2 ``` But I expect a url like this: ``` http://mysite.com/?param1=var1&param2=var2 ``` In function manual it says: $params array additional GET parameters (name=>value). Both the name and value will be URL-encoded. But it doesn't seem to work like that. How I can generate the expected URL? Thanks.

Original source