7

How to get base URL in a Yii CConsoleApplication application?

I tried Yii::app()->request->getBaseUrl(true) and ended up with the following error.

Undefined index: SERVER_NAME (/var/www/yii/framework/web/CHttpRequest.php:279)

rob006
  • 21,383
  • 5
  • 53
  • 74
Harish Ambady
  • 12,525
  • 4
  • 29
  • 54

5 Answers5

13

There is no request object in a console application. the request object in a web application its an instance of CHttpRequest, if you are generating URLs in an offline task, you have to configure the baseUrl in some other way, perhaps in the configuration:

"request" => array(
    'hostInfo' => 'http://localhost',
    'baseUrl' => '/yii-project/index-test.php',
),

// OR

'request' => array(
    'hostInfo' => 'http://localhost',
    'baseUrl' => '/yii-project',
    'scriptUrl' => 'index-test.php',
),
Asgaroth
  • 4,274
  • 3
  • 20
  • 36
3

For Yii2 advanced template, create params.php file if it doesn't exist in config directory of your console or common app and paste the following code:

return [
   'frontendUrl' => 'http://yourdomain.com'
];

So that it can be accessed in the following way in console:

echo Yii::$app->params['frontendUrl'];
pravindot17
  • 1,199
  • 1
  • 15
  • 32
0

You have to add in config/console.php in components array

'request' => array(
    'hostInfo' => 'http://localhost',
    'baseUrl' => '',
    'scriptUrl' => '',
),

and also add urlManager so it will remove index.php?r=site/action from the url and you will have pretty urls

'urlManager' => array(
    'urlFormat' => 'path',
    'showScriptName' => false,
    'rules' => array(
        '<controller:\w+>' => '<controller>/index',
        '<controller:\w+>/<id:\d+>' => '<controller>/view',
        '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
        '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
    ),
),
ursuleacv
  • 1,119
  • 14
  • 16
-3

Please try the following wayt to get the base url page,

echo Yii::app()->getBaseUrl(true);
Vinoth Babu
  • 6,724
  • 10
  • 36
  • 55
-3

get the home url like this:

http://www.demo.local

echo Yii::app()->homeUrl;
Baby Groot
  • 4,637
  • 39
  • 52
  • 71